Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery form submit validation

I have following form:

<form id="testForm" action="country_Save">
   Country Name:<input type="text" id="countryName" />  
   <input type="submit" id='saveCountry' value="Add Country" />
</form>

and following JQuery for validating textfield

$('#testForm')
   .jqxValidator({  rules : [
          {
              input : '#countryName',
              message : 'Country Name is required!',
              action : 'keyup, blur',
              rule : 'required'
          }],
          theme : theme
});

How can i use this validation when I am submitting a form?

like image 639
edaklij Avatar asked Nov 24 '12 12:11

edaklij


People also ask

How do I validate a form before submitting?

What is form validation. Before submitting data to the server, you should check the data in the web browser to ensure that the submitted data is in the correct format. To provide quick feedback, you can use JavaScript to validate data. This is called client-side validation.

How Prevent form submit in jQuery validation fails?

You need to do two things if validation fails, e. preventDefault() and to return false. This really works.


3 Answers

Bind a function to the submit event of the form. Return false in this function if any of the form fields fail validation.

For example:

$('form').on('submit', function() {
    // do validation here
    if(/* not valid */)
        return false;
});
like image 100
Soumya Avatar answered Nov 07 '22 19:11

Soumya


Try this please:

     $('#testForm').on('submit', function() {
         return $('#testForm').jqxValidator('validate');
     });
like image 27
Gajotres Avatar answered Nov 07 '22 19:11

Gajotres


Form validation have a wide set of Javascript and jQuery libraries... My sugestion is a simple jquery.com plugin.

PS: jqxValidator is a method from the jQWidgets framework? if you (reader) not need so heavy/complex plugin, see bellow pure jQuery, else @Gajotres writed the best solution (!).


Using only jQuery and basic Javascript.

For both, "plug library" and "writing your own validation methods", first check if the direct use of jQuery is what you need.

Here a code that do all what the question say to need: validation on blur, keyup and "when submitting".

function validate(){
    var cnv = $('#countryName').val();
    if (!$.trim(cnv)) {
        alert('Country Name is required!');
        return false;
    } else { return true; }
}

$('#testForm').submit(validate);
$('#countryName').bind('blur keyup', validate);
like image 30
Peter Krauss Avatar answered Nov 07 '22 17:11

Peter Krauss