Reputation: 699
I have an HTML form with a button which when clicked, it will check whether or not the fields are empty. Here is part of my code which does the validation(it works):
var errorMessage ="";
if (document.getElementById('username').value == "")
{
errorMessage += "Please enter a username \n";
document.getElementById('username').style.borderColor = "red";
}
if (document.getElementById('fname').value == "")
{
errorMessage += "Please enter a first name \n";
document.getElementById('fname').style.borderColor = "red";
}
if (document.getElementById('lname').value == "")
{
errorMessage += "Please enter a last name \n";
document.getElementById('lname').style.borderColor = "red";
}
if (errorMessage != "")
{
alert(errorMessage);
}
My problem is because I have more fields which require validation, I am wondering if there is a better way of doing this rather than having so many if statements (I'm trying to have as little code as possible). I was thinking of using a switch case statement but would that work? Any suggestions?
Upvotes: 5
Views: 1560
Reputation: 35960
Since every other answer either suggests writing your own validation code, or use some big, heavy frameworks like Angular, I'd like to suggest using small, specialized libraries for validtion, like Parsley.js (although it depends how do you define "small" - Parsley ships either in jQuery/Zepto dependand version or standalone weighting around 42kB).
Using Parsley, your could write very little code to validate a form. Just load this library and then use rules defined in custom HTML attributes, like data-type="email"
.
Here's an example from their webpage (I stripped down all parts not important in your question. Here is a full example, for your reference):
<form id="demo-form" data-validate="parsley">
<input
type="text"
name="email"
data-trigger="change" <!-- parsley's attributes: data-... -->
data-required="true"
data-type="email" /> <!-- E-mail rule -->
<input
type="text"
name="website"
data-trigger="change"
data-type="url" /> <!-- URL rule -->
<textarea
name="message"
data-trigger="keyup"
data-rangelength="[20,200]">
</textarea>
</form>
There are, of course, other libraries which can do same thing, like validate.js, but I prefer Parsley.js' aproach using data-
attributes - it's a very clear separation of concerns and nice example of "extending" HTML.
Upvotes: 0
Reputation: 206121
I'd go with this way, using data-* attribute to store the error messages:
<form id="myForm" name="myForm">
<input type="text" name="username" id="username" data-err="Please enter a username" />
<input type="text" name="fname" id="fname" data-err="Please enter a first name" />
<input type="text" name="lname" id="lname" data-err="Please enter a last name"/>
<input type="submit" />
</form>
function formValidator(){
var inputs = this.getElementsByTagName('input');
var allErrors = '';
for(var i=0; i<inputs.length; i++) {
var el = inputs[i];
var data = el.dataset.err;
if(data && el.value.trim() === ''){
allErrors += data +'\n';
}
}
if(allErrors){
alert(allErrors);
return false;
}else{
alert('All fine. Submit!');
}
}
document.myForm.onsubmit = formValidator;
Upvotes: 1
Reputation: 17521
You can use a table with data of fields and then just iterate over it.
var fields = [[document.getElementById("username"),"Please Enter Your Username"],
[document.getElementById("fname"), "Please Enter Your First Name"],
[document.getElementById("lname"), "Please Enter Your Last Name"]];
function Check()
{
var error = [];
for (var i in fields)
{
if (fields[i][0].value == "")
{
error.push(fields[i][1]);
fields[i][0].style.borderColor = "red";
}
}
if (error.length)
window.alert(error.join(",\n"));
return !error.length;
}
Note: probably you want o make sure that the value isnt empty so I would suggest you using something like: fields[i][0].value.replace(/\s/g, "") == ""
instead.
Upvotes: 2
Reputation: 1585
If you want to go with plain Javascript without any Client side Javascript framework, or HTML5 you cant do that.
You can look at HTML5 as suggested by @bios, or you can use frameworks such as:
These would ease your validation requirements and make code cleaner.
If you want something more sophisticated, you can go for full fledged client side MVC frameworks such as:
But these are too heavy if you want just form validation.
Upvotes: -1