javascript validation phone number - javascript

alright, whats wrong with my script, JShint is throwing three lines of red code saying i have issues in my variable and my if/else statement. I am trying to validate if the phone number is a valid USA phone format
$( "#phone" ).focusout(function telephone() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("");
return false;
} else {
var re = \d{3}[\-]\d{3}[\-]\d{4};
if(re.test(document.getElementById("phone").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});

Firstly, you don't need a name for closure function. Secondly you have not enclosed regex with /..../.
var re = /\d{3}[\-]\d{3}[\-]\d{4}/;

You Should try this.
$(function(){
$("#phone").change(function telephone() {
if (this.value === "" || this.value === null) {
$("#error_messages").text("");
return false;
} else {
if (/\d{3}[\-]\d{3}[\-]\d{4}/.test($(this).val())) {
$("#error_messages").text("");
return true;
} else {
$("#error_messages").text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" id="phone" />
<span id="error_messages"></span>

This is an expression tested on http://tools.netshiftmedia.com/regexlibrary/# for numbers. change it to /^\d{3}[\-]\d{3}[\-]\d{4}$/ in your JS code and apply regex code within /..../ in that tools
I applied
^\d{3}[\-]\d{3}[\-]\d{4}$
It's ok with your numbers :

Related

Validate a form only if every input is empty

Well, the question's pretty self-explanatory. I've been looking for a while and haven't found a proper way to do this kind of validation.
All I need to do is to run an error message if all the inputs are empty. If one of them is filled, then I don't need to stop the form from submitting.
I thought something like:
function checkForm() {
$('input').each(function(){
if( $(this).val() == "" ){
return false;
}
});
});
But this will stop my form if there's, at least, one input without data.
Any ideas? Thanks in advance.
Reverse your logic. I.e. return true if any input has a value, otherwise return false:
function checkForm() {
$('input').each(function() {
if ($(this).val() !== '') {
return true;
}
});
return false;
};
Reverse your logic since you want to check if the value is non-empty for one input field.
Also you probably want to return from your actual function and not from the callback which has no effect.
function checkForm() {
let bool = false;
$('input').each(function(){
if( $(this).val() !== '' ){
bool = true;
}
});
console.log(bool);
return bool;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<button onclick="checkForm()">check</button>

How to check if textbox value is not number?

<!DOCTYPE html>
<html>
<body>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
<script>
$(document).ready(function () {
jQuery("#text").on("change", function () {
var x = $('#text').value;
if (isNaN(x))
{
window.alert("You have entered not a number");
return false;
});
});
});
</script>
</body>
</html>
I am trying to write javascript code to check if the given value is not number.If not i would like to give error message? If it is number I would like to check if it is integer and between 0 and 100.
Basically you need to convert to an Int before compare it with NaN which means something like:
var x = $('#text').value;
if ( isNaN( parseInt(x) ) ) {
// Not a decimal number.
}
There are a lot of syntax errors in your code.
Your selector checks your div for the change event instead of your input, which means it will never trigger the code.
You should use .val() to get the value of an element when using jQuery selectors instead of .value.
You can also use the this keyword inside the event handler to get the referenced element.
Besides that there were some misplaced ) and } in your code.
Below I have included an working sample of your code.
$(document).ready(function() {
jQuery("#text > input").on("change", function() {
var x = $(this).val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
} else if (x > 0 && x < 100) {
alert("number in between 0 and 100");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
function numberOrNot(var input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
this will return true if your input is number, otherwise it will return false
try this code
you enter direct input on change or write id for input and pass it to javascript
$(document).ready(function() {
jQuery("input").on("change", function() {
var x = $('#text').val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
}
else{
if(x>=0 && x<=100)
{
window.alert("You have enter write number");
}else{
window.alert("You enter number between 0 to 100");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CommentBox">
Some text :
<input type="text" id="text" />
</div>
You can use try-catch and put as many conditions you want in try block Like this. I have put three conditions for now.
<script type="text/javascript">
function Validation(){
var number1=document.LoginForm.number1.value;
try{
if(number1==""){
throw "Empty";
}
if(isNaN(number1)){
throw "Not a Number";
}
if(number1<0 || number1>100){
throw "Out of range";
}
}
catch(err){
if (err=="Empty"){
alert("Number 1 and Number 2 fields cannot be empty");
}
if (err=="Not a Number"){
alert("Please enter a number");
}
if(err=="Out of Range"){
alert("Out of Range");
}
return false;
}
//return true;
}
</script>

Validate textarea input for alphanumeric value

I want to validate textarea which is an Address field, it must contains both of letters and numbers, at least 1 number .
for example : "Laksda Adisucipto street, no 22A."
but when i just type : "Laksda Adisucipto street" (without number) it can show alert "you must enter at least 1 number"
i'm using Twitter Bootstrap and Validator.js
here's my code
HTML :
<div class="form-group col-md-12">
<label for="address" class="control-label"><span>*</span> <?php echo $this->lang->line('address');?></label>
<textarea class="form-control" id="address" rows="5" required name="address" data-error="Address is required"></textarea>
<span class="help-block with-errors"></span>
</div>
JS :
<script>
$('#address').change(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(($('#').value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
} );
Try this
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
you can check it here: http://jsfiddle.net/oa6eewck/
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
This function will allow only characters and numbers,it will be good for a input text field but since you are having text area "spaces" and "commas" and "periods" are expected right.
So better follow the expression follows :
$('#address').blur(function()
{
var hasNumber = this.value.match(/^[a-zA-Z0-9\s .,]+$/);
if ( hasNumber) {
return true;
} else {
alert("message");
return false;
}
});
$('#address').on('change', function () {
var hasNumber = this.value.match(/\d/);
var isAlfa = this.value.match(/^[0-9a-zA-Z]+$/);
if ( hasNumber && isAlfa ) {
return true;
} else {
alert("message");
return false;
}
});
FIDDLE
adeneo's solution is right. but I think isAlfa should have following value
var isAlfa = this.value.match(/^[A-Za-z\d(-.,) ]+/);

jquery custom validation script without plugin?

i used to use jquery validation plugin but because of lack of this plugin with wysiwyg plugins i wrote a simple script to validate my form
i tried to do it like this
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article body</li>');
return false;
}
if ($('#ArticleTitle').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article title</li>');
return false;
}
$('#errors').hide();
return true ;
}
i found to 1 problem when it validate the form it's validating it field by field so the errors messages doesn't appear at once
i tried to do something like
var errors = [];
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
errors.push('<li>please enter your article body</li>');
var invalid = 1 ;
return false;
}
if ($('#ArticleTitle').val() == 0) {
errors.push('<li>please enter your article title</li>');
var invalid = 1 ;
return false;
}
if(invalid == 1){
$.each(errors , function(i, val) {
$('#errors').append(errors [i]);
});
}
$('#errors').hide();
return true ;
}
i tried to push errors as array elements and loop through them in case of invalid is true
bu this one doesn't work at it all ?
is there any way to make it work ?
if ($('#editor').val() == 0) // This is checking if value is 0
This does not make sense..
Try
if ($('#editor').val() == '') //Instead check for empty string
EDIT
Also you seem to be hiding the error's div in the end.
$('#errors').hide();
Try this code Instead
$('#validate').on('click', function() {
var errors = [];
var html = '<ul>' ;
valid = true;
$('#errors').empty();
if ($('#editor').val() == '') {
errors.push('<li>please enter your article body</li>');
valid = false;
}
if ($('#ArticleTitle').val() == '') {
errors.push('<li>please enter your article title</li>');
valid = false;
}
if (!valid) {
html += errors.join('') + '</ul>'
$('#errors').append(html);
}
else{
$('#errors').hide();
}
return valid;
});​
DEMO

Calculation issue With JQuery

I know it is very simple.But Still it is not working.I am multiplying a input number with a fixed number,but is not showing the expected result.it always shows the Error message "Please enter some value" even i enter some integer e.g. 6.
This is Html Code.
<input type="text" class="cc" id="getdata" />
<div id="result"> <input type="text" id="show" /></div>
<input type="button" value="calculate" id="calculate" />
This is JQuery Code.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#input").val() != '' && $("#input").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#input").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});
Any help will be highly appreciated.
Can anyone tell me please how to concatenate all clicked values of different buttons in a textbox?I want to show previous and current clicked value of button in a textbox.
Thank you.
Do you not mean #getdata? Where is #input?
Replace ("#input") with ("#getdata") in your code.
Check out this fiddle.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
} else {
$("#result").html("Please enter some value");
}
});
});​
You have no input whose id is "input". The jquery selector #somestring is looking for an element whose id is somestring.
Replace ("#input") by ("#getdata") in your code.
There is no field with the ID input in the HTML you posted, yet your jQuery is looking for one. Perhaps you meant $('#show')
With jQuery issues, ALWAYS suspect the selector before even wondering what else might be wrong. Confirm it actually finds the elements you think it does - never assume.
console.log($('#input').length); //0
if ($("#input").val() != '' && $("#input").val() != undefined) {
You dont have any field anywhere in your markup with the id input!
I think you intended all the instances of #input in that script to be #getdata, but you should also only read its value once into a variable and use that:
$("#calculate").click(function () {
var val = $('#getdata').val();
if (val != '' && val != undefined) {
$("#result").html("total value is::" + parseInt(val) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
Live example: http://jsfiddle.net/82pf4/
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});
Checkout this Fiddle
I think that is what you want.
<input type="text" class="cc" id="getdata" />
<input type="button" value="calculate" id="calculate" />
<div id="result"></div>​
<script>
$("#calculate").click(calculate);
$("#getdata").keypress(function(ev){
if(ev.keyCode == 13)
calculate();
});
function calculate()
{
var $getData = $("#getdata");
var $result= $("#result");
if ($getData .val() != '' && $getData .val() != undefined && !isNaN($getData .val()))
{
$result.append((parseInt($getData .val()) * 5) + "<p>");
}
else
{
$result.append("Please enter some value<p>");
}
$getData .val("").focus();
}
​
</script>

Categories