www.webdeveloper.com
Page 3 of 3 FirstFirst 123
Results 31 to 36 of 36

Thread: Validating textarea

  1. #31
    Quote Originally Posted by \\.\ View Post
    HTML5 add more than just AUDIO and VIDEO to the game
    Which are redundant tags to OBJECT and should never have been made new tags. Their very existence pisses on the entire intent of "real" HTML 4 (aka strict) and it's intent... along with all the other pointless idiotic redundancies. Native support for media formats? GREAT. New tags for NOTHING, and doing so in a manner that promotes vendor lock-in and then selling it to people with magic kool-aid claiming it's fighting vendor lock-in? Sorry, that sets off my BS alarm.

    Quote Originally Posted by \\.\ View Post
    but also add some useful elements to things like the <input> tags for one, things like date which is a calendar date picker so that means all those date picker
    I assume you mean the new input types -- which yes, are cute. I just wish they were consistent cross browser and cross OS. The date one is nice, the color picker... depends on the browser. I've had a lot of people complain about them and ask for scripted equivalents because at least you can control the appearance of them. I'd like them better if there were CSS hooks for styling them and what they show for options were consistent cross-browser.

    But the handful of improvements are outweight by HTML 5's idiotic pitching in the trash the logical document structure based on professional writing, loosening of the structural rules to the point validation is useless while pissing on accessibility to non-visual UA's, the re-introduction of old redundancies we were supposed to be getting rid of, introduction of new redundancies for no good reason, tags for things that shouldn't even HAVE tags, and so forth.

    Quote Originally Posted by \\.\ View Post
    Other items such as a canvas for drawing and animating complex object
    Which is JS NOT HTML, and as such has no damned business having a tag in the markup. Would have been FAR more useful if they had simply let us attach a 2dContext or 3dContext to ANY existing DOM element. Even when I use it -- and I've done my own little demo with it (that stopped dead in it's tracks from becoming a game as it was too slow and the state of JS controlled audio is pathetic in terms of latency) -- I add CANVAS from the script since, well... since it does JACK **** without scripting so why the devil would it be in the markup? The only reason it seems to exist as a markup element is to be redundant to NOSCRIPT. Has NO business being part of a markup "specification"; but then MOST of the things people call HTML 5 aren't and/or have not a blasted thing to do with belonging in a markup spec... and I do mean "specification" (yes, I'm making air quotes with my fingers).

    So your current appraisal of HTML5 is not taking on board some of the advancements that have been long over due.

    Quote Originally Posted by \\.\ View Post
    I really don't see the need for <label> tags given you have to click them to put the cursor in the <input tag, much simpler to click on the actual element and the point of focus is so that the visitor can type without having to click on the element.
    Because making the target area LARGER (since it's not "must", it's "MAY") is a bad thing... because following the semantic structural rules of building a form so you have relational markups for non-visual UA's (including search) is a bad thing?!?

    Yeah, GOD FORBID we actually bother following the structural rules of building a form that have been around since the form tag was introduced sixteen years ago... :/

    Quote Originally Posted by \\.\ View Post
    Nothing as yet has been done about highlighting the erroneous element, should the OP want it I am sure that they are capable of adding it or asking for help with it.
    Given what I've seen so far, I wouldn't make that assumption.

    Quote Originally Posted by \\.\ View Post
    Anonymous functions, if you search for articles discussing them, you will soon find that anonymous functions carry more overhead than regular functions.
    BULL! Well, not ENTIRELY bull. If you use a self calling anonymous function like you would a smalltalk instance or PHP singleton, they use NO MORE OVERHEAD than a normal function with global variables, all it does is restrict scope. Hell, the ONLY article I could find that seems to say anything even CLOSE to what you are saying on the subject USES ONE IN HIS FINAL EXAMPLE!!! [i]Either my google-fu is failing me, or you didn't read any of the articles deep enough![/b]

    Single instance anonymous functions like the self calling:

    Code:
    (function test() {
    // do something
    }();
    Have NO MORE OVERHEAD than if you made all the var inside it global by declaring them before the function. OOH, not that. (Hell, it's the DESIRED EFFECT I'm aiming for when using it). In other words, for those the argument means not a blasted thing if that's what you want -- mind you some people complain because the variables are not released, but if that's what you are trying to accomplish, that's when you use it!

    Passing an anonymous function ONCE because it will only exist ONCE:

    Code:
    addEvent(e, 'change', function() {
    // do something
    });
    NO more than if it were a separate function, could even be LESS as it's only saved as the target result!

    The ONLY time it's a problem is when you have a whole SLEW of them:

    Code:
    for (var t = 0; t < list.length; t++) addEvent(list[t], 'focus', function() {
    // do something
    });
    As every single instance creates a NEW function instance as it's not passed by reference. In that case, YES, this:

    Code:
    function test() {
    // do something
    }
    
    for (var t = 0; t < list.length; t++) addEvent(list[t], 'focus', test);
    Would use less memory.

    For some weird reason there are people who seem to turn that last corner-case into a "never use" when that's NOT WHAT IT MEANS!

    Though if you'd care to link to some of those articles I'm not finding on Google or DDG, Maybe I'm wrong. Prove it; of course you probably won't since that's what happened the last time I had a go-around with someone who had said misunderstanding of it.

    Quote Originally Posted by \\.\ View Post
    No one said anything about using the onload="... tag or window.onload which I do avoid as much as possible.
    IF you are going to hook the elements from the scripting instead of the other way around -- which I advocate as scripting has no blasted business in the markup -- you have to wait for the DOM to be built. That either means onload, DOMReady, and it's kin/kine, or loading before </body>. That's why I mentioned it. Otherwise we'd have onblur, onchange, onfocus on every blasted input/select manually as well as the onchange on the form. To blazes with that or that type of thinking.

    Quote Originally Posted by \\.\ View Post
    name-space collision happen when you have many working on a large project, a lone programmer is less likely to encounter such problems and when they do its something that can be resolved, why you place such emphasis on a problem that is quite mute I don't know.
    So in other words you don't work with others, code for others, and assume that this is going to be the only scripting the OP is going to try and put on a page? Sound battle plan there alright...

    Quote Originally Posted by \\.\ View Post
    As for tables, if you don't like them don't use them, simples.
    It's not about like or dislike, it's about semantic markup; a big fancy term for USING HTML PROPERLY! -- I'm actually getting sick of using the term "semantic markup" as it's more a way to avoid offending people who CAN'T SEEM TO BE BOTHERED TO LEARN WHAT THE HTML TAGS ARE, WHAT THEY ARE FOR, OR HOW TO USE THEM PROPERLY!

    Tables are for tabular data. PERIOD. Using them on non-tabular data just to have rows and columns is NOT USING HTML PROPERLY!... Not using LABEL on the text for your INPUT/SELECT/TEXAREA is NOT USING HTML PROPERLY!. Using colspanned TD with a class and a bold tag instead of a CAPTION is NOT USING HTML PROPERLY!

    Heavens forbid we expect people to learn how to actually use HTML tags for what they mean and where they should be used. No, let's just let people sleaze out tags any old way and to hell with accessibility, graceful degradation, or the dozens of other things using HTML is supposed to be about if you make even the slightest effort to understand what it is and what it's for...

    The laugh being many so called "experts" call HTML "easy" and then can't be bothered to use it right? Again, air quotes around "experts".

    Lands sake, even if that WERE to be built using the tabular relationship instead of the PROPER SEMANTICS OF THE LABEL TAG, the 'labels' should be <th scope="row"> and not TD.
    Last edited by deathshadow; 08-19-2014 at 06:11 PM.

  2. #32
    Join Date
    Oct 2013
    Posts
    613
    Just to tweek deathshadow's nose this all comes in at 3.4kb; about half that if using a "modern" browser since the JS file won't be loaded:

    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>My form</title>
    <link rel="stylesheet" type="text/css" href="formstyles.css">
    <script src="focus.js"></script>
    <!--[if IE ]>
    <script type="text/javascript" src="ievalidation.js"></script>
    <![endif]-->
    </head>
    <body>
    
    <h1>My Cool Form</h1>
    
    <!--[if IE ]>
    <form method="post" name="form1" onSubmit="return echeck(this);" action="#">
    <![endif]-->
    
    <!--[if !IE]>-->
    <form method="post" name="form1" action="#">
    <!--<![endif]-->
     
     <label for="name">Name</label><input type="text" id="name" name="YourName" size="16" required><br>
    
     <span class="red">**</span> <label for="phone">Phone</label><input type="tel" id="phone" name="PhoneNumber" size="15"><br>
     
     <label for="email">Email</label><input id="email" type="email" name="EmailAddress" size="27" required><br>
           
     <label for="street">Street Address</label><input id="street" type="text" name="StreetAddress" size="27" required><br>
           
     <label for="city">City</label><input type="text" id="city" name="City" size="27" required><br>
           
     <label for="zip">Zip</label><input type="number" min="10000" id="zip" name="ZipCode" required><br>
           
     <label for="county">County</label><select id="county" name="County" required>
    		<option value="">Choose one</option>
    		<option value="Bucks">Bucks</option>
    		<option value="Chester">Chester</option>
    		<option value="Delaware">Delaware</option>
    		<option value="Montgomery">Montgomery</option>
    		<option value="Philadelphia">Philadelphia</option>
    	   </select><br>
           
     <div id="messageLabel"><label for="message">Message</label></div> <div id="messageHolder"><textarea id="message" name="Message" cols="25" rows="7" required></textarea></div>
    
     <p class="red clear">** <i>Optional</i></p>
    
     <input class="button" type="submit" value="Send Message">
    
    </form>
    
    </body>
    </html>
    CSS (formstyles.css):
    Code:
    body {
    	background-color: #000;
    	color: #fff;
    }
    form {
    	line-height: 2em;
    }
    label {
    	margin-right: 0.5em;
    }
    #messageLabel, #messageHolder {
    	vertical-align: top;
    	float: left;
    }
    #name, #street, #city {
    	text-transform:capitalize;
    }
    .red {
    	color: red;
    }
    .clear {
    	clear: both;
    }
    .button:hover {
    	cursor: pointer;
    }
    JavaScript (focus.js):
    Code:
    onload=function(){
    	document.getElementById('name').focus();
    }
    JavaScript (ievalidation.js):
    Code:
    function echeck(o){ // o is the onsubmit="return echeck(this);" line in your form submit
    	try{
    	var	evt = !event ? o : event;
    		evt = event ? evt:window.event;
     	if (evt.preventDefault) evt.preventDefault();
     	evt.returnValue = false;
    	evt.cancelBubble = true;
    	}catch(e){
    		o.addEventListener('submit', function(evt){ evt.preventDefault(); }, false );
    		}
    	var	emailAddress	= o.EmailAddress.value,
    		yourName	= o.YourName.value,
    		street		= o.StreetAddress.value,
    		city		= o.City.value,
    		county		= o.County[o.County.selectedIndex].value,
    		zip		= o.ZipCode.value,
    		msg		= o.Message.value,
    		r		= false,
    		e		= "";	
    
    	e = ( msg.length==0 ) ? "Message" : e;
    	e = ( county=='' ) ? "County" : e;
    	e = ( zip.length<5 ) ? "Zip Code" : e;
    	e = ( city.length==0 ) ? "City" : e;
    	e = ( street.length==0 ) ? "Street Address" : e;
    	var parts = emailAddress.split("@");
    	domain = parts.length>1 && parts[1].indexOf(".")>0 ? true : false;
    	e = (!domain) ? "Email Address" : e;
    	e = ( yourName.length==0 ) ? "Your Name" : e;
    	
    	if( e.length ){
    		alert( "Please Enter your " + e );
    		o[(e.replace(" ",""))].focus();
    		return false;
    	}
    		
    	o.submit();
     	return true;
    }
    Some slight changes to the JS provided by \\:\ (with many thanks )

    Beat that Mr. "CutCodeDown" with your misused XHTML DOCTYPE. It all validates. But go ahead and stick your beloved, but not necessary, <fieldset> tagset in there (<div> will do the job in XHTML1.0 STRICT). It only adds 21 bytes. Then closing all the unnecessarily "unclosed" tags such as <meta> and <br> adds more unnecessary code. BTW do you know why we (well, you) write <br/> as <br /> in XHTML? Why the space between "r" and "/"??? Netscape. Really. Why are you writing code in 2014 for a browser that disappeared 10+ years ago?

    Look, the whole point in my mind is that IE9- doesn't deal with HTML5 form attributes, so let's target the script to those browsers. All modern browsers (FF, Chrome, Safari, IE10+, iOSanything, AndroidAnything) will validate the form (i.e. won't let it submit) using HTML5 form attributes.

    For the OP's edumacation, IE10+ doesn't ID itself as MSIE. In fact those browsers say they're "like Gecko" -- which is a laugh because Gecko is Firefox's rendering engine. IE10+ also doesn't support "IE conditional statements". So by targeting "IE" with conditional statements we only load the JavaScript file, and the corresponding <form> tag that calls it, if the browser is IE9-. Therefore only the browsers that need it get/load it.

    DS: "But but but HTML5 is only a DRAFT not a 'recommendation'. AND it's a train-wreck!" Tell that to the developers at Google (Chrome), Mozilla (Firefox), and Opera. Oh wait, hmm, real Opera (12.x-) was one of the first adopters of HTML5 (about version 8-9).

    And lastly DS, before you go spewing more bilge about <th scope=""> please, PLEASE, PLEASE, P L E A S E (!) read Note 1 on this page:
    http://www.w3.org/TR/WCAG20-TECHS/H63.html
    ("For simple tables that have the headers in the first row or column then it is sufficient to simply use the TH elements without scope.")
    Last edited by Kevin2; 08-19-2014 at 07:32 PM.

  3. #33
    Quote Originally Posted by Kevin2 View Post
    Just to tweek deathshadow's nose this all comes in at 3.4kb; about half that if using a "modern" browser since the JS file won't be loaded:
    Actually, that's one of the few scenarios I advocate using IE conditionals, to hide legacy IE specific scripting. I can get behind that.

    Quote Originally Posted by Kevin2 View Post
    <link rel="stylesheet" type="text/css" href="formstyles.css">
    No media target? REALLY?

    The IE CC's around the form tag? Pointless garbage since again, if you hooked the element from the scripting, you wouldn't need to put that nonsense in the markup; of course to hook the DOM has to exist, so it's either load before </body> try to use DOMContentLoaded which is buggy at best, nonexistent at worst in IE -- or wait for onload.

    Classes like "red" and "clear" also are trash, since that's presentation. At least say "required" or use a tag you're not using for anything else so you don't even need classes in the first place. Bold is actually appropriate since it's a notification; NOT that I'd mark the optional field since that's questionable accessibility and back-assward.

    Code:
     <input type="number" min="10000" id="zip" name="ZipCode" required>
    You guys do know there are zip codes that start with zero, right? Like say... pretty much ALL of New England? 03431 checking in, used to live in 02345 and 02360... Also restricting it to 'number' means you can't enter a +4. There ARE places (APO's for example) where omitting the +4 is guaranteed to be a "straight to the dead letter office".

    Though honestly as HTML 5 crap goes, it's not bad. Again most of my problem with 5 is with the redundant tags, pointless tags and throwing logical document structure out the window.

    Of course you've got DIV for nothing and floats in the CSS doing the job of inline-block and vertical align, EVEN in legacy versions of IE. NO clue why you think a text-transform is warranted on the elements you put it on...

    Quote Originally Posted by Kevin2 View Post
    JavaScript (ievalidation.js):
    ... and here's the real ****storm.

    You're passing "this" because you used onsubmit... so what the blue blazes is this:
    Code:
    	try{
    	var	evt = !event ? o : event;
    		evt = event ? evt:window.event;
     	if (evt.preventDefault) evt.preventDefault();
     	evt.returnValue = false;
    	evt.cancelBubble = true;
    	}catch(e){
    		o.addEventListener('submit', function(evt){ evt.preventDefault(); }, false );
    		}
    Even for?!?

    Code:
    	var	emailAddress	= o.EmailAddress.value,
    		yourName	= o.YourName.value,
    		street		= o.StreetAddress.value,
    		city		= o.City.value,
    		county		= o.County[o.County.selectedIndex].value,
    		zip		= o.ZipCode.value,
    		msg		= o.Message.value,
    Hardcoded so useless for working with other forms and has to be changed should you want to add/remove fields.

    Though this is the REAL gem:
    Code:
    	e = ( msg.length==0 ) ? "Message" : e;
    	e = ( county=='' ) ? "County" : e;
    	e = ( zip.length<5 ) ? "Zip Code" : e;
    	e = ( city.length==0 ) ? "City" : e;
    	e = ( street.length==0 ) ? "Street Address" : e;
    So have all those conditions overwriting each-other instead of reporting, so only the last one that fails is reported? That's just LOVELY. Nothing like "keep on running code blind" even if a problem has already been detected... The nun I took programming lessons from thirty years ago would have put down the wood and gotten the metal yardstick for the whipping I'd have gotten for that.

    Code:
    	var parts = emailAddress.split("@");
    	domain = parts.length>1 && parts[1].indexOf(".")>0 ? true : false;
    	e = (!domain) ? "Email Address" : e;
    Sloppiest most incomplete e-mail check EVARRRR.

    Code:
    	if( e.length ){
    If you had set e to numeric 0 or false, you could simply have checked (e) instead of (e.length)

    Code:
    		o[(e.replace(" ",""))].focus();
    cute, but wouldn't it have been more efficient to just trap this on the element when it fails?

    Code:
    	o.submit();
     	return true;
    }
    Double submit? LOVELY... since you start a submit, then return true which would simply have let the submit run?!? :/ You do realize you're doing:

    onSubmit="return echeck(this);"

    RIGHT?!?

    You really should learn some more JS before you start writing it.

    Quote Originally Posted by Kevin2 View Post
    Beat that Mr. "CutCodeDown" with your misused XHTML DOCTYPE.
    Misused? Love to hear the logic behind that.

    Quote Originally Posted by Kevin2 View Post
    But go ahead and stick your beloved, but not necessary, <fieldset> tagset in there (<div> will do the job in XHTML1.0 STRICT).
    Unless of course you're in something where semantics matter like JAWS that will actually leverage that fieldset to say "this section is user input" as opposed to DIV where it's assumed to be non-controllable content.

    Quote Originally Posted by Kevin2 View Post
    It only adds 21 bytes. Then closing all the unnecessarily "unclosed" tags such as <meta> and <br> adds more unnecessary code.
    ... and provides for clearer code since you have a clear distinction between the closes of EMPTY elements and the opening of non-empty elements should they not both fit on screen.

    Quote Originally Posted by Kevin2 View Post
    BTW do you know why we (well, you) write <br/> as <br /> in XHTML? Why the space between "r" and "/"??? Netscape.
    ... well, and I find it clearer / stands out better. As much as I like code minimalism, I won't sacrifice clarity on that altar. After all, I'm a Wirth kind of guy.

    Quote Originally Posted by Kevin2 View Post
    Look, the whole point in my mind is that IE9- doesn't deal with HTML5 form attributes, so let's target the script to those browsers.
    Too bad you sent it to all versions of IE... including 10+.

    Quote Originally Posted by Kevin2 View Post
    All modern browsers (FF, Chrome, Safari, IE10+, iOSanything, AndroidAnything) will validate the form (i.e. won't let it submit) using HTML5 form attributes.
    Which I like the idea, but I'm just not sold on it as the browser specific implementations leave a LOT to be desired. (Yes Firefox, I'm looking at YOU!)

    Quote Originally Posted by Kevin2 View Post
    DS: "But but but HTML5 is only a DRAFT not a 'recommendation'. AND it's a train-wreck!" Tell that to the developers at Google (Chrome), Mozilla (Firefox), and Opera.
    You mean the same people who tossed everything that made Opera worth using in the trash by turning it into chrome with the Opera logo slapped on it any old way, the folks who still don't have a properly working HTML 4 or CSS 2.1 implementation, and the people who just re-marked a sixteen year old table implementation bug as "NEW"? The ones promoting vendor lock-in in the name of fighting vendor lock-in? RIGHT.....

    Quote Originally Posted by Kevin2 View Post
    Oh wait, hmm, real Opera (12.x-) was one of the first adopters of HTML5 (about version 8-9).
    When they still didn't have HTML 4 or CSS2 working right. Nothing like implementing the new flashy crap when you don't even have the subset working yet. Real plan for success right there. (but then I was a Opera fan for the stuff I could do with the UI, NOT for the rendering engine. I could give a flying purple fish about the rendering engine as a browser USER).

    Quote Originally Posted by Kevin2 View Post
    And lastly DS, before you go spewing more bilge about <th scope=""> please, PLEASE, PLEASE, P L E A S E (!) read Note 1 on this page:
    Which would be great if the implementations supported it -- but both Apple's reader and JAWS choke on it... I used to advocate that one myself until I found out it didn't actually WORK.

    Even if it did, that still means they'd be TH, not TD.

    Of course, you know that part of the WCAG was written from a non-semantic perspective (not a shock due to it's age) since where's the THEAD and TBODY? HTML 3 / 4 Tranny style "assumed" I presume?

    Of course you can tell it's outdated HTML 3.2 garbage from the demo table that follows, what with the BORDER attribute on the table. Of course that the TESTS section contradicts the informative section above it:

    Tests
    -------------------------
    Procedure

    For each data table:

    1) Check that all th elements have a scope attribute.

    2) Check that all td elements that act as headers for other elements have a scope attribute.

    3) Check that all scope attributes have the value row, col, rowgroup, or colgroup.

    Expected Results

    All checks above are true.
    So if you follow that note you quoted, it should actually FAIL a WCAG 2 conformance test.

    Fun how the conformance test for that section doesn't match the text explaining it, no? That's the big problem with WCAG 2.0, it's like it was written by five schiophrenics and a rhesis monkey; WCAG is a GREAT idea -- but there's a reason it's a guideline, not a spec. You want hard fast rules, that's what specifiations are supposed to be for... No matter how hard the WTFWG tries to pass off their soft loose mess of "the new transitional" as a "specification".

    Which is really what HTML 5 is -- the new transitional. There is a handful of nice things, but it's weighed down by a whole bunch of garbage. We need a "5 strict" that tries to do what 4 Strict was about -- like removing redundancies, simplifying the specification, and lending an ear to accessibility and usability for users; as opposed to HTML 5's "let's just blindly document everything out there and to hell with making sites simpler, faster or easier to use".

    All the new "structural tags", the loosening of the structural rules so there's no real distinction between block and inline-level, VIDEO, AUDIO, it all just reeks of "we can't get people to pull their heads out of 1997's backside, so to hell with it we'll just let everyone sleaze along any old way" -- pitching the entire concept behind HTML 4 STRICT in the trash.

    Progress? Really looks like the worst of 1997 to me.

    In any case, I'm gonna do a rewrite 5-style of what you just posted to show what I mean.

  4. #34
    ... and here we go, basically what you were hardcoding, as something automated. Admittedly it relies on the input[name] as the trigger for zip or e-mail validation (boo), but it also uses the content of the previous node labels in the error message for required. Also, notice the fun trick for detecting the required attribute right back to IE 5.

    First up, we gut the markup and get it properly structured:
    Code:
    <!DOCTYPE html>
    <html lang="en"><head>
    
    <meta charset="UTF-8">
    
    <link
    	type="text/css"
    	rel="stylesheet"
    	href="screen.css"
    	media="screen,projection,tv"
    >
    
    <title>Form Validation Demo</title>
    
    </head><body>
    
    <h1>Form Validation Demo</h1>
    
    <form method="post" action="#">
    	<fieldset>
    
    		<label for="name">Name</label>
    		<input type="text" id="name" name="name" required>
    		<br>
    
    		<label for="phone"><b>**</b> Phone:</label>
    		<input type="tel" id="phone" name="phone">
    		<br>
    
    		<label for="email">E-Mail Address</label>
    		<input id="email" type="email" name="eMail" required>
    		<br>
    
    		<label for="street">Street Address</label>
    		<input id="street" type="text" name="street" required>
    		<br>
    
    		<label for="city">City</label>
    		<input type="text" id="city" name="city" required>
    		<br>
    
    		<label for="zip">Zip Code</label>
    		<input type="text" id="zip" name="zip" required>
    		<br>
    
    		<label for="county">County</label>
    		<select id="county" name="county" required>
    			<option value="">Choose one</option>
    			<option value="Bucks">Bucks</option>
    			<option value="Chester">Chester</option>
    			<option value="Delaware">Delaware</option>
    			<option value="Montgomery">Montgomery</option>
    			<option value="Philadelphia">Philadelphia</option>
    		</select>
    		<br>
    
    		<label for="message">Message</label>
    		<textarea id="message" name="message" cols="25" rows="7" required></textarea>
    	</fieldset>
    
    	<div>
    		<p>** <em>Optional</em></p>
    		<input type="submit" value="Send Message">
    	</div>
    
    </form>
    
    <!--[if IE ]><script src="ieValidate.js"></script><![endif]-->
    
    </body></html>
    The CSS I added a bit more style to as the zig-zag of labels was driving me nutty.

    Code:
    body {
    	background:#000;
    	color:#FFF;
    }
    
    fieldset {
    	border:0;
    	padding:0;
    }
    
    label,
    input,
    select,
    textarea {
    	display:inline-block;
    	vertical-align:top;
    	margin-bottom:0.5em;
    }
    
    label {
    	width:7em;
    	line-height:1.5em;
    	text-align:right;
    }
    
    fieldset input,
    fieldset select,
    fieldset textarea {
    	width:100%;
    	max-width:20em;
    	padding:0.25em;
    	border:1px solid #888;
    }
    
    #zip {
    	width:5.5em;
    }
    
    #county {
    	width:auto;
    }
    
    form b,
    form p {
    	color:#F00;
    }
    real world I'd have .validate before all the loose tags.

    Then the self-hooking script... that uses the simple alert how you were, but auto-attaches to all forms to implement required.

    Code:
    (function() {
    
    	function nFirst(e) {
    		e = e.firstChild; while (e && (e.nodeType != 1)) e = e.nextSibling; return e;
    	}
    	
    	function nNext(e) {
    		do { e = e.nextSibling; } while (e && (e.nodeType != 1)); return e;
    	}
    	
    	function nPrev(e) {
    		do { e = e.previousSibling; } while (e && (e.nodeType != 1)); return e;
    	}
    	
    	function errorAlert(n, message) {
    		alert(message ? message : 'Please enter your ' + nPrev(n).innerText);
    		n.focus();
    		window.event.returnValue = false;
    	}
    	
    	function validate() {
    		var e = nFirst(window.event.srcElement), n;
    		do { if (e.tagName == 'FIELDSET') {
    			n = nFirst(e);
    			while (n) {
    				if (n.getAttribute('required') != null) switch (n.tagName) {
    					case 'INPUT':
    					case 'TEXTAREA':
    						if (n.value == '') { errorAlert(n); return; }
    					break;
    					case 'SELECT':
    						if (n.options[n.selectedIndex].value == '') { errorAlert(n); return; }
    					break;
    				}
    				if (n.name) switch (n.name) {
    					case 'zip':
    						if (!n.value.match(/^\d{5}([\-]?\d{4})?$/)) {
    							errorAlert(n, "Invalid Zip Code\nMust be 00000 or 00000-0000 format");
    							return;
    						}
    					break;
    					case 'eMail':
    						if (!n.value.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/)) {
    							errorAlert(n, 'Invalid E-Mail Address');
    							return;
    						}
    					break;
    				}
    				n = nNext(n);
    			}
    		}} while (e = nNext(e));
    	}
    	
    	function setup() {
    		var f = document.getElementsByTagName('form');
    		for (var i = 0; i < f.length; i++) f[i].attachEvent('onsubmit', validate);
    	}	setup();
    	
    })();
    A hair larger, but it does a few things yours doesn't... like attach itself... like not be hardcoded to only check certain elements for required and instead just searching for it. I switched to DOM walking instead of getElementsBy inside it as it is actually faster and lower memory use, even with the non-input elements like BR and LABEL in the way. Which would be SO much easier if legacy IE supported nextElementSibling... or that nextSibling wasn't 'proper' in IE9 -- lose/lose on that one

    It also means cleaner/simpler/clearer markup as you can get rid of a bunch of nonsense like the two copies of the FORM tag and the CC's around it. Less markup always wins out over less JS. You're going to use more code somewhere, put it in the files that can be cached across page-loads.

    As always, live copy here:
    http://www.cutcodedown.com/for_others/ASPSQLVB/simple5

    ... and you can add/remove required fields until blue in the face without even touching the script.

    Though as I may have mentioned, I probably wouldn't even HAVE a scripting fallback or even client side validation in the first place -- it makes ANY difference in bandwidth or user convenience of a form, you've probably got rubbish labels, design and instructions in the form. Oh noes, you might have to resend it populated from the server after checks you HAVE to run again server-side anyways, nots thatz.

  5. #35
    Oh, also note that since you were using the script for IE9/lower only, you can get rid of feature detection as IE9/earlier have window.event available and likewise if using attachEvent you only need srcElement removing the need to look for target, as well as that you only need to use returnValue... all those other values are for "modern" browsers.

    There are times when writing jScript for IE only the result ends up so clean I often wish RoW would simply work that way. Admittedly, I get the same feeling when I write user.js for FF/Opera since a single browser target just makes things so simple. Ah well, at least with IE10+ for the most part FINALLY getting on the same page as everyone else things will get better eventually.

  6. #36
    Join Date
    Aug 2014
    Posts
    2
    figure out why the form validating is working good up until I get to the textarea(message) field?....after typing characters into the textarea(message).

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles