116

I made a simple validation form using jQuery. It's working alright. The thing is I'm not satisfied with my code. Is there another way around to write my code with the same output result?

$(document).ready(function(){

$('.submit').click(function(){
    validateForm();   
});

function validateForm(){

    var nameReg = /^[A-Za-z]+$/;
    var numberReg =  /^[0-9]+$/;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var names = $('#nameInput').val();
    var company = $('#companyInput').val();
    var email = $('#emailInput').val();
    var telephone = $('#telInput').val();
    var message = $('#messageInput').val();

    var inputVal = new Array(names, company, email, telephone, message);

    var inputMessage = new Array("name", "company", "email address", "telephone number", "message");

     $('.error').hide();

        if(inputVal[0] == ""){
            $('#nameLabel').after('<span class="error"> Please enter your ' + inputMessage[0] + '</span>');
        } 
        else if(!nameReg.test(names)){
            $('#nameLabel').after('<span class="error"> Letters only</span>');
        }

        if(inputVal[1] == ""){
            $('#companyLabel').after('<span class="error"> Please enter your ' + inputMessage[1] + '</span>');
        }

        if(inputVal[2] == ""){
            $('#emailLabel').after('<span class="error"> Please enter your ' + inputMessage[2] + '</span>');
        } 
        else if(!emailReg.test(email)){
            $('#emailLabel').after('<span class="error"> Please enter a valid email address</span>');
        }

        if(inputVal[3] == ""){
            $('#telephoneLabel').after('<span class="error"> Please enter your ' + inputMessage[3] + '</span>');
        } 
        else if(!numberReg.test(telephone)){
            $('#telephoneLabel').after('<span class="error"> Numbers only</span>');
        }

        if(inputVal[4] == ""){
            $('#messageLabel').after('<span class="error"> Please enter your ' + inputMessage[4] + '</span>');
        }       
}   

});
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
jhedm
  • 1,398
  • 4
  • 20
  • 31
  • 3
    yes , you can use jquery validation script for make it more better. – Devang Rathod Feb 25 '13 at 04:48
  • 10
    http://codereview.stackexchange.com/ – it's what you are looking for – Alexander Feb 25 '13 at 22:11
  • 3
    You can use HTML5 form validation: `$('form')[0].checkValidity()` – niutech Apr 22 '16 at 15:48
  • if the main focus is simplicity, valijate jquery plugin is promising. it is a startup plugin. but, it uses some interesting way of validation. here is the link for there guide. http://valijate.com/Docs.php – bula May 29 '17 at 07:43
  • Update the email validate regex to: var emailReg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; – Sadee Oct 10 '18 at 10:11

2 Answers2

322

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
Sparky
  • 98,165
  • 25
  • 199
  • 285
19

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

Devang Rathod
  • 6,650
  • 2
  • 23
  • 32
  • 3
    jQuery validator is good, but I think a validator that takes the new HTML5 validation features into account is even better, e.g. http://ericleads.com/h5validate/. – Matt Browne Feb 25 '13 at 04:56
  • @MattB., Never heard of that one, but [jQuery Validate plugin also takes HTML5 features into account](http://jsfiddle.net/vEhbH/), although I'm not sure why you'd need/want to use both together. – Sparky Feb 25 '13 at 17:07
  • 2
    Devang, `jquery.form.js` is **not required** to use the code you've shown. – Sparky Feb 25 '13 at 17:14
  • @Sparky Unless you have a particular aesthetic already designed that you really like for validation messages, allowing an HTML5-supporting browser to display validation messages in the default way is often nicer, where the validation plugin only gets used as a fallback for displaying error messages on older browsers, and for validation logic HTML5 doesn't support (without extra Javascript). But this is as much my personal preference as anything. – Matt Browne Feb 25 '13 at 17:15
  • 1
    @MattB., typically, people using jQuery are looking for the cross-browser consistency you get by moving away from browser features which vary greatly from brand to brand. I also prefer to stick with popular plugins that have a huge base of support, and if [the developer is also part of the jQuery Team](http://bassistance.de/jquery-plugins/jquery-plugin-validation/), all the better, IMO. – Sparky Feb 25 '13 at 17:22