October 13, 2012

Check whether an input string contains number

Question by Udara S.S Liyanage

I want to check whether an input string contains number.

I am trying to validate an input field. I want it to contain only alphabet, not numbers.

Answer by Starx

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

While implementing

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

Update: To check if a string has numbers in them, you can use regular expressions to do that

var matches = val.match(/d+/g);
if (matches != null) {
    alert('number');
}
September 30, 2012

how to prevent script tags in zend form

Question by Awais Qarni

Hi there I am just testing my own developed application and got a problem. I entered

<script>window.location = "http://www.google.com";</script>

in Zend_Form_Element_Text element. I pressed submit and the value is saved. After saving value I redirect the user to listing and when it redirects to listing, script tag executes and it goes to google.com.

My form element looks like

 $first_name = new Zend_Form_Element_Text('first_name');
 $first_name->setRequired(true)
            ->addFilter('StringTrim')
            ->addValidator('StringLength', false, array(2, $metaData['first_name']['LENGTH']))
            ->setDecorators(array('ViewHelper', 'errors'));

I want to know how can I prevent the user to enter such kind of values? Is there any built in validation or any other way?

Answer by vascowhite

Well done for testing your app, many people don’t bother. Don’t worry about storing that string in your database it won’t do any harm and changing it may give you problems with other, valid, entries. As vstm says, escape it when you use it.

However, as you are specifically talking about a ‘First Name’ field there is probably some more validation that you can do, such as rejecting any names with a / in them. I’m not aware of any language that has that as part of a name. If there is, I’d love to know how it’s pronounced. You could probably add . = and some others to that list too, but don’t get too carried away.

You should carefully consider every field in your form with regards to what input you would reasonably expect to receive and validate the input accordingly. Anything that doesn’t pass validation is rejected. A string like '<script>window.location = "http://www.google.com";</script>' should certainly never pass validation for a field expecting a person’s name.

Personally, I never filter input. It either passes validation and is accepted, or it doesn’t and is rejected. I can’t make good input out of bad input by filtering it, so it gets rejected and the user is asked to re-enter their data. For example, using a StripTags filter on

<script>window.location = "http://www.google.com";</script>

will leave you with

window.location = “http://www.google.com”;

which is still not a valid name and should be rejected.

Your validation will never work 100% of the time and that is why you should always escape values received from user input before echoing them out to the browser.

Zend Framework has a raft of validators that you could use and don’t forget the validators and filters that PHP has already available for you. Use them properly and you will greatly reduce the risk of malicious input hurting either your application or, more importantly, your users.

Those validators and filters are there for you to use, but neither PHP nor Zend Framework know what kind of data you are expecting, so it is very important that you read the documentation and learn exactly how they work, how to use them and when to use them.

There is an excellent resource at The Web Application Security Project that every web dev should be forced to read on pain of death.

tl;dr
Validate input and escape output.

Answer by Starx

You can use filters to restrict input from the user. Read about the filters

There is a filter in Zend Framework called Zend_Filter_StripTags which will give you the option to strip all or selected tags. Here is an example from the site itself.

$filter = new Zend_Filter_StripTags();     
print $filter->filter('<B>My content</B>'); 

As result you will get the stripped content ‘My content’.

On your case the following

$first_name->setRequired(true)
            ->addFilter('StringTrim')
            ->addFilter('StripTags') //Here a add a filter to strip tags
            ->addValidator('StringLength', false, array(2, $metaData['first_name']['LENGTH']))
            ->setDecorators(array('ViewHelper', 'errors'));
May 29, 2012

jQuery Validate – Success event?

Question by Probocop

I am using the jQuery Validate plugin on my site, and then submitting the form via ajax. Is there an event I can use when the entire form is valid?

Answer by Starx

There is no event for this. Just check the status using a simple if statement.

if($("form").valid()) {
 //go ahead
}

But, if you are trying to have a workaround solution to catch the valid event, you can do something like this

$("form").submit(fucntion() {
    if($(this).valid()) {
       //go ahead
    } else {
       //do some error handling
    }
});
April 18, 2012

jQuery validation – How to not accept a file extension

Question by Maxime Lepers

I would like to find a way to refuse a specific extension in a text field at form submission.

I have a field where you can specify a URL but this URL shouldn’t link to a PDF file.

I figured that there is a jQuery validation methods called accept that does exactly the contrary of what I want to do.

Is there a way to use with a not() function or something similar? It would be way easier than creating a custom validation method.

Answer by Starx

Here is any idea

var ext = $('#fieldid').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','jpg', ...]) == -1) {
    alert('invalid extension!');
}
April 12, 2012

Jquery custom validation non numeric

Question by Brian Perin

I’m trying to write a custom validation function for jquery. The rule should be that the field cannot ONLY be numeric. I know how to write only numeric or only alpha but I want the rule to say that a value of “12345” would fail, but “12345A” would be validated

This is what I have for non numeric

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !value.match(/[0-9]+/);
},"Only alphabatic characters allowed.");

but I can’t figure out how to do not ONLY numeric.


Working script

Here are three rules that might be helpful, the last one is the one that answers this question.

 jQuery.validator.addMethod("noSpace", function(value, element) { 
    return value.indexOf(" ") < 0 && value != ""; 
}, "No spaces please");

jQuery.validator.addMethod("alpha", function(value, element) {

    return this.optional(element) || /^[a-z]+$/i.test(value);
},"Letters only please.");

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || isNaN(Number(value));
},"String cannot be numeric");

Answer by Elliot Bonneville

Use parseInt (which returns NaN if the operand isn’t strictly a number) like this:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(parseInt(value));
},"Only alphabatic characters allowed.");

Don’t use != in this case or you could wind up with this unpleasant situation.


According to Ken Browning‘s comment, parseInt might not be appropriate here. Try this instead:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(Number(value));
},"Only alphabatic characters allowed.");

Answer by Starx

I think this regex should be enough

/[a-z]/i.test(value);

Usage

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !(/[a-zA-Z]/i.test(value));
},"Only alphabatic characters allowed.");
April 9, 2012

Validate Int Value in JavaScript

Question by user70192

I am trying to figure out how to ensure that a user enters an int into a text field with JavaScript. Currently, I have the following:

var myVal = $("#myField").val();
if (isInt(myVal)) {
  alert("Awesome!");
} else {
 alert("No Good");
}

function isInt(i) {
    if ((i != null) && (i != undefined) && (i.length > 0)) {
        alert(typeof i);
        return (typeof i == 'number' && /^-?d+$/.test(i + ''));
    }
    return false;
}

If I enter 123 into the text field, I have noticed that the typeof i is “string”. I’m not sure how to perform this kind of validation. Can someone please let me know? I was suprised I didn’t have any success when I Googled this.

Answer by Engineer

​function isInt(myVal) {
    return /^[+-]?d+$/.test(myVal);
}

Answer by Starx

Here is a short and sweet way

function isInt(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
April 7, 2012

Error message not get cleared while clicking the reset button

Question by vivek

I am using jquery.validate.js file to validate an input form, It works fine, my problem is the error messages are not get cleared while clicking the reset button in the form.

how to get clear the form?

here is the code

 <script type="text/javascript" src="js/jquery.js"></script>

 <script type="text/javascript" src="js/jquery.validate.js"></script>


  javascript function

      $(document).ready(function(){        

        $("#demo-form").validate({    
          rules: {
            name: "required",
            address: "required",
       }

HTML Code

<div><input type="text" id="name" name="name" /></div>

<div><input type="text" id="address" name="address" /></div>

<div> <input type="submit" id="submit" value="Validate!" />
      <input type="reset" id="reset" value="Reset" />   

Answer by Starx

Basically, when you click the reset button. It will be responsible for clearing the fields, not the label. Normally, jquery validate plugin, keeps its validation messages in labels. So in order to clear them, use

$('label.error').remove();

call this on the click of reset button
where it is needed.

April 5, 2012

how can i make a javascript based form checkbox validate with javascript before sending my form

Question by phj

Hi i have a contact form on my site, In this form i got a javascript checkbox button.

This is the end code of my form: this div tag is my checkbox:

<p><label for="agree">(*) I agree whit the transport terms and conditions:</label><div id="cb"></div></p>
<p>hi
<input name="Submit / Send" type="submit" class="submit" id="Submit / Send" tabindex="370" value="Submit / Send" />
<p id="error_zone" style="visibility:hidden;">Errors: There are some errors in the form. Please correct them.</p>
</p>

This is the javascript text button:

<script type="text/javascript">
    var cbh = document.getElementById('cb');
    var val = '1';
    var cap = '';

    var cb = document.createElement('input');
    cb.type = 'checkbox';
    cbh.appendChild(cb);
    cb.name = val;
    cb.value = cap;
    cbh.appendChild(document.createTextNode(cap));
</script>

also i make use of spry validation for my other form elements.
I would like to validate the checkbox with javascript to create a captcha checkbox!
Is it posible to let pop up a validation masage and and not disturbe the spry validation?!
Its important that if javascript is turned off the form als can’t submit any more.

Hope someone can help me. thanx alot for your time!

i’m trying to encomplish this: http://uxmovement.com/forms/captchas-vs-spambots-why-the-checkbox-captcha-wins/

snippet of spry validation:

<script type="text/javascript">
var errorsOnSubmit = function(form){
 var ret = Spry.Widget.Form.validate(form);
 var errorZone= document.getElementById('error_zone');
 if (!ret){
      errorZone.style.visibility = 'visible';
      errorZone.style.backgroundColor = 'red';
 }else{
      errorZone.style.visibility = 'hidden';
 }
 return ret;
}
</script>
<script type="text/javascript">
var spryselect1 = new Spry.Widget.ValidationSelect("spryselect1", {isRequired:false,  invalidValue:"1", validateOn:["blur", "change"]});
var spryselect2 = new Spry.Widget.ValidationSelect("spryselect2", {isRequired:false, invalidValue:"1", validateOn:["blur", "change"]});
var spryselect3 = new Spry.Widget.ValidationSelect("spryselect3", {isRequired:false, invalidValue:"1", validateOn:["blur", "change"]});

Answer by Starx

Give an ID to the checkbox after you created the element

cb.type = 'checkbox';
cb.id = 'mycheckbox';
cbh.appendChild(cb);

Now, you can select the element using document.getElementById('mycheckbox') and the validate it.

Here is a snippet to validate the checkbox

var myform = document.forms("yourformname");
myform.onsubmit = function() {

    //validate the checkbox
    var checkb = document.getElementById('mycheckbox');
    if(checkb.checked != true) { 
       alert('not checked');
    }

    //rest of the validation
};

Update 1:

Haven’t tested but should work

var errorsOnSubmit = function(form){

  //validate the checkbox
  var checkb = document.getElementById('mycheckbox');
  if(checkb.checked != true) { 
     alert('not checked');
  }

 var ret = Spry.Widget.Form.validate(form);
 var errorZone= document.getElementById('error_zone');
 if (!ret){
      errorZone.style.visibility = 'visible';
      errorZone.style.backgroundColor = 'red';
 }else{
      errorZone.style.visibility = 'hidden';
 }
 return ret;
}
April 3, 2012

javascript multiple checkbox validation

Question by skylab

I would like to use this simple script with my form to make sure I have at least 1 box checked but I have a feeling something is wrong, most likely at the getElementsByName tag. I always get the pop up box no matter if I have items checked or not.

<script language="javascript">
function validate() {
    var chks = document.getElementsByName('id[][]');
    var hasChecked = false;
    for (var i = 0; i < chks.length; i++) {
        if (chks[i].checked) {
            hasChecked = true;
            break;
        }
    }
    if (hasChecked == false) {
        alert("Please select at least one.");
        return false;
    }
    return true;
}
</script>

and the form, which may or may not end up with more checkboxes in the end:

<form 
enctype="multipart/form-data" 
method="post" 
action="formsubmission.php"
name="form_type" onSubmit="return validate()">

<input id="attrib-8-10" type="checkbox" value="10" name="id[8][10]">
<label class="Checkbox" for="attrib-8-10">thick</label>
<input id="attrib-8-11" type="checkbox" value="11" name="id[8][11]">
<label class="Checkbox" for="attrib-8-11">medium</label>
<input id="attrib-8-12" type="checkbox" value="12" name="id[8][12]">
<label class="Checkbox" for="attrib-8-12">thin</label>

Answer by Starx

var chks = document.getElementsByName('id[][]');

Does not select any element, as you have specied all the index on the elements .

Here is how you can do it?

var chks= document.getElementsByTagName('input');
for (var x=0; x < chks.length; x++) {
    if (chks[x].type.toUpperCase()=='CHECKBOX' && chks[x].checked == true) {
        hasChecked = true;
        break;
    }
}
March 12, 2012

Jquery Empty validation for text box

Question by user1263374

I’ve a text box in a form,when a user submits the form,it should check whether the user has filled it,other validation would be have some min characters,he has to fill.

here is my code,which is not validating


$('.textboxid').bind("submit", function() {
  if($(this).val() == "") {
    jQuery.error('Fill this field');
    return false;
  }
});

Answer by Starx

Your code is not validating because, you are binding submit event on a textbox. You should use forms to do that.

Apart from sudhir’s answer, which will work fine. To provide an alternative to it. You can use regex validations too.

An Nice example, which adds errors messages after the textbox as well.

$("#yourFormId").submit(function() {
    var inputVal= $("#yourTextBoxId").val();
    var characterReg = /^([a-zA-Z0-9]{1,})$/;
    if(!characterReg.test(inputVal)) {
        $("#yourTextBoxId").after('<span class="error">Maximum 8 characters.</span>');
    }
});
...

Please fill the form - I will response as fast as I can!