i need a validate textbox which is accepted like this $250.00 here is '$' will accepted only one time and then never accepted '$' as well as '.'(dot).
You could use a masked input for example
your mask would be
$('#input').mask('$9?.99');
You can do:
var x = document.getElementById('your-text-box').value;
if(x.match(/^\$[0-9]+\.[0-9]+$/) == null) {
// invalid
}
else {
// valid
}
The regex /^\$[0-9]+\.[0-9]+$/ will match any string meeting the following constraints
Should start with a $
Should have 1 or more numbers after the $
Should have a . after the first set of numbers
Should end with 1 or more numbers after the .
Is jquery an option?
Here is a jquery solution. First of all I wouldn't validate expecting user to put '$'. I would put that outside the form and just allow people to enter the amount. That's weird, but I guess I don't really have the context on what you are doing. See Jquery validation:
$("#myform").validate({
rules: {
field: {
required: true,
digits: true
}
}
});
This is using digits to allow only numbers. Otherwise if you really need $ in there you need to create a custom validation rule.
<!-- wherever your jquery file is -->
<script src="../../jquery.min.js"></script>
<input type="text" id="cost"><input type="button" id="check" value="Check!">
<script>
// jquery solution
$(document).ready( function (){
$('#check').click( function (){
var cost = $('#cost').val();
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
});
});
</script>
Of course you can use pure java script as well to reduce the dependency
<input type="text" id="cost">
<input type="button" id="check" value="Check!" onClick="check();">
<script>
// Pure Javascript Solution
var check = function (){
var cost = document.getElementById('cost').value;
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
}
</script>
Related
I have a input field which is a percent value, i am trying for it to display as % when not focused in and when focused in it will loose the %, also the input field needs to avoid chars on it. I'm using a type"text" input field with some jQuery.
$(document).ready(function() {
$('input.percent').percentInput();
});
(function($) {
$.fn.percentInput = function() {
$(this).change(function(){
var c = this.selectionStart,
r = /[^0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
$(this).focusout(function(){
$(this).val(this.value + "%");
});
$(this).focusin(function(){
$(this).val(this.value.replace('%',''));
});
};
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2"></input>
<input class="percent" value="4"></input>
on the snippet it does not behave the same as on my app, not sure why but the intended result is for it to erase any char that is not a digit or "only" 1 % sign.
Would change this approach only slightly:
use keypress (and eventually paste) to block invalid characters
use parseFloat (or int if you don't allow decimals) to remove leading 0's --> '00009.6' => '9.6%'
However I'd use <input type="number"> (btw: </input> closing tag is invalid HTML)
these days with a % sign just after the input. (number type has better display on mobile)
(function($) {
$.fn.percentInput = function() {
$(this)
// remove formatting on focus
.focus(function(){
this.value = this.value.replace('%','');
})
// add formatting on blur, do parseFloat so values like '00009.6' => '9.6%'
.blur(function(){
var r = /[^\d.]/g,
v = this.value;
this.value = parseFloat(v.replace(r, '')) + '%';
})
// prevent invalid chars
.keypress(function(e) {
if (/[^\d.%]/g.test(String.fromCharCode(e.keyCode)))
e.preventDefault();
});
};
})(jQuery);
$(document).ready(function() {
$('input.percent').percentInput();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2%">
<input class="percent" value="4%">
It is my understanding that the snippet you provided is the desired behavior, but your app isn't behaving in the desired way you've demonstrated. So, the question is: what's different between this snippet and your app? Does your app throw any errors into the console?
When I encounter problems like this, I'll usually run my page through an HTML validator. Sometimes, invalid html can corrupt more than you'd think.
When I put your html into a standard HTML5 template, the validator finds these errors in your snippet:
Basically, it is saying that you don't need </input>. Do this instead:
<input class="percent" value="2">
<input class="percent" value="4">
Perhaps this is completely unrelated, but I thought I'd mention it. I'd put your actual app through the html validator to see if you find more errors that could be ultimately corrupting your javascript's ability to achieve the desired behavior showcased by your snippet.
1.XXX-XXX-XXXX
2.XXXXXXXXXX
I would like to know the regular expression of the format.
Modifying the existing sources will yield results.
var regExp = /^01([016789]?)-([0-9]{3})-([0-9]{4})$/;
var regExp = /^01([016789]?)[0-9]{3}[0-9]{4}$/;
A statement to check the condition.
I wonder if the contact form is also correct.
var test is a text field that receives input.
if(!regExp.text) {
alert(""phone number format is not valid.");
document.getElementById('phone').focus();
return ;
}
I'm not quite sure what you are trying to achieve, but maybe this example helps:
https://jsfiddle.net/xu9fcbxt/
Notice: jQuery required
Code:
JS:
$(document).ready(function(){
var regExp = /^01[5-7][1-9]-[0-9]{3}-[0-9]{4}/;
$('#phone').focusout(function(){
var text = $('#phone').val();
if(!regExp.test(text)){
alert('not a valid phone number');
}
});
});
HTML:
<input id="phone" type="text" />
This would check if the number has a format like 0151-123-4567
I'm using the pattern attribute in an HTML5 input. It works fine, until I add a custom message using setCustomValidity. All this is supposed to do is
Sets the validationMessage property of an input element.
But instead my pattern is ignored. If I comment out the setCustomValidity, the pattern works.
HTML
<form>Country code:
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
</form>
JS
$('input').get(0).setCustomValidity("It's wrong");
$('input').on('input', function () {
console.log($(this).prop('validity'));
var valid = $(this).get(0).checkValidity();
console.log(valid); });
http://jsfiddle.net/hrtsz50s/
use reportValidity(); insted of checkValidity(); and when you call the function clear the validity with an empty string first!
$('input').get(0).setCustomValidity("It's wrong");
$('input').on('input', function () {
this.setCustomValidity('');//Add this!!
console.log($(this).prop('validity'));
var valid = $(this).get(0).reportValidity();//here
console.log(valid); });
edit
Got it working in this fiddle: http://jsfiddle.net/hrtsz50s/1/
I have some text inputs on my site for phone numbers. I want to keep all numbers in one format not some like 123-456-7890 and others 1234567890. I've tried writing a code to change this but it is giving me an error of Uncaught ReferenceError: changePhone is not defined.
Here is my code:
<input type="text" id="phone" onblur="changePhone(this.id)">
function changePhone(id){
$(id).text(function(i, number) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
return number;
});
}
When running validation my code checks out as valid so I am not understanding why it doesn't work.
On a side note: Is there a PHP solution to achieve this or is jquery my best option?
EDIT: Here is a fiddle of my code: http://jsfiddle.net/4uk9hhtc/
There are so many things wrong with this.
$(id) does not work because you need a # before ID. You are doing $('whateverID') should be $('#whateverID')
The .text()does not work because you are running on an input element.
Your fiddle is missing jquery, and the code should in <head>
http://jsfiddle.net/4uk9hhtc/13
function changePhone(id){
var number = $("#"+id).val().replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
alert( number )
}
OR you could just use jquery and get rid of inline onclick like in the other answers
Here is something that actually works
$(function() {
$('#phone').on('blur', function(){
var val = ""+this.value;
this.value = val.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="phone" />
Pure JS with inline invocation
function changePhone(field) {
var val = ""+field.value;
field.value = val.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
}
<input type="text" id="phone" onblur="changePhone(this)"/>
Pure jQuery solution. Your fiddle isn't including jQuery by the way. I'm making assumptions that you know how to include jQuery correctly. You should be using val().
http://jsfiddle.net/2kLywwpu/1/
<input type="text" class="phone" id="theText">
using
var textbox = $('#theText').on('blur', function(){
textbox.val(function(i, number) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
return number;
});
});
Here's a fiddle that's not using your regular expression so you can see that the basic functionality works.
http://jsfiddle.net/2kLywwpu/2/
i m trying to do a validation using jquery.
Enter Account no:
here is my html code
<input type="text" name="Assets" id="Assets" size="25" /><br />
<div id="eb"> Please Enter Valid Account no </div>
Enter Amount<input type="text" name="Liability" id="Liability" size="25" /><br />
and here is my jquery code
$(document).ready(function(){
$("#Assets").change(function(){
var Assets = $('input#Assets').val();
var expression=/[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
if (Assets == "" || Assets == " ") {
$('#eb').show();
}
else if(Assets.test(expression)){
$('#eb').hide();
}
$('#eb').toggle();
}
i want to display a mesage when user write a account no then at a time he can see the message that Please Enter Valid Account no and if he insert correct then that message can be hide.
here is my jsfiddle - http://jsfiddle.net/BzdfN/5/
please help
Try this code:
$(document).ready(function () {
$("#Assets").change(function () {
var Assets = this.value;
var expression = /[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
if (Assets.match(expression)) {
$('#eb').hide();
} else {
$('#eb').show();
}
});
});
This is a suggestion for more simple code. Notice I used match() which takes a regex as paramenter, if you want to use test() you should use the value/string as paramenter and use like expression.test(Assets).
Fiddle
About your code/fiddle:
you missed adding jQuery library to the fiddle
you missed ) closing the change() function
you missed }) closing the ready() function
you used test() with wrong order, check my text above about match() and test()
your fiddle with corrections: Fiddle
jQuery was not included and multiple syntax errors
$(document).ready(function () {
var expression = /[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
$("#Assets").change(function () {
$('#eb').toggle(!expression.test(this.value));
})
})//missing brackets
Demo: Fiddle
Try this - http://jsfiddle.net/dangoodspeed/BzdfN/9/ I made a bunch of changes, including activating jQuery, closing some functions, and reversed Assets and expression for the .test call
else if(expression.test(Assets)){