JavaScript regular expression mobile phone number format - javascript

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

Related

Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery

I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format. This should occure .on("input") meaning as the user types it should secure the right input format.
A wrong char should be replaced with a blank.
Format Example: 1.000 1.281 21212.000 21212.810Nothing like this:1.02.12 or 1919,201,00 Only a dot between the two Number blocks.
This is what i have so far:
Regex 1:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[^0-9]/g,'');
});
Regex 2:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
Regex 3:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
I think i am doing something wrong with the replace() method.
Unfortunately none of them work as i want to. Any help is appreciated.
Here is the FIDDLE
Should Work in IE11
You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser
const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;
$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />
</body>
</html>
try this one,
^[0-9]*(\.|,)?[0-9]*$
this take below cases:
1111,
.0000
123,12
12.12
12345
but if you want only
111,11
11.11
12345
so please use this
^[0-9]+(\.|,)?[0-9]+$
to force use dot/comma please use this
^[0-9]+(\.|,)[0-9]+$
add this code
$("#testId").keyup(function(){
var vals = $("#testId").val();
if(/^[0-9]*(\.|,)?[0-9]*$/g.test(vals))
$("#testId").val(vals);
else
vals = vals.replace(/.$/,"");
$("#testId").val(vals);
});
and change input type to
type="text"

Textbox should allow only Hexa decimal values

I have a textbox and i can enter only 2 digits. What i want is that user can only input Hexa values in it like 12,a0,0a (2 digits) if user enters any ather value , it will not be entered. Can you please help.
<input onkeyup=validateHexa(this); class='nbb' maxlength='2' value='??'/>
function validateHexa(ele){
var control = ele.value;
var regExp = new RegExp(/^([A-Fa-f0-9]{2}){8,9}$/);
if (!regExp.test(control))
ele.value="true";
}
You can do something like this:
function replaceInput(ele) {
var re = /[^A-Fa-f0-9]/g;
ele.value = ele.value.replace(re, '');
}
<input onkeyup=replaceInput(this); class='nbb' maxlength='2' placeholder='??' pattern="[A-Fa-f0-9]{2}"/>
JSFiddle
hello there you should try Regular expression like ([aA-hH 0-9]{2})
please comment if any issue :)

Validating Data using JS Regex

I am using javascript regex for validating user entered date in format mm/yyyy. I have made regex for this and its working fine, but when I enter ab/abcd its still validating it.
This is my JS and HTML code
function validate() {
var name = document.getElementById("name").value;
var pattern = /\d|\/|\d{4}/;
if (pattern.test(name)) {
alert(name +" has alphanumeric value");
return true;
} else {
alert("Name is not valid.Please input alphanumeric value!");
return false;
}
}
Date: <input type="text" name="name" id="name" />
<input type="submit" value="Check" onclick="validate();"/>
How can I validate the entered date in mm/yyy format,
I am using Jquery DatePicker which allows to select date in this format, and the datepicker also allows manual input. like this Date Picker
Is there any alternate suggestion for this?
Updated:
Try the pattern below instead:
var pattern = /^\d{2}\/\d{4}$/;
See the working code at:
JSFiddle
Another fiddle for extracting the month:
JsFiddle2

date.parse not sure how to implement

I am looking for some date.parse() help for JavaScript. I have been searching different forums and sites and still have not been able to find a decent example of how to implement this. I am taking a beginning web design class and my instructor has asked for me to do this : "Set the placeholder text for the text box to “Enter a date.” Add an empty paragraph tag set to the document. In a separate JavaScript file code the event handler for the button to set the paragraph text to state whether or not the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and the special value NaN (not a number) otherwise. NaN can be check for using the built-in function isNaN(). (You may want to refer to your online resources for more information on the Date object, NaN , and isNaN().)" I have been to a ton of websites that show the string but I need a dumbed down example of how to actually use it. here is my html code for the button:
<body>
<form>
<input type="text" id="dateTextInput" size="40" placeholder="Please Enter A Date">
<input type="button" id="addButton" value="Enter a Date">
</form>
<p></p>
</body>
and here is what I have for my .js file:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick() {
var textInput = document.getElementById("addDateButton");
var dateString = textInput.value;
if (dateString == "") {
alert("Please enter a date");
}
else {
my issue is after my else, if that is even appropriate. I am lost as how to implement the date.parse function. I know it's date.parse(variable) but not sure how to make sure it can be a valid format. Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way? Or is there a simpler option? A link to a great guide would also be helpful, if an answer cannot be provided here. Thank you for your time.
Update; here is what I am using now. It halfway works. It alerts for an empty set. I just can't get the parse to alert:
function handleButtonClick() {
var textInput = document.getElementById("dateTextInput");
var dateString = textInput.value;
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
if (dateString == "") {
alert("Please enter a date");
} else {
return(valid);
}
}
I hope everthing is understandable.
<form id="dateForm">
<!-- pattern just allow such format X.X.XXXX Or XX.XX.XXXX Or X.XX.XXXX Or XX.X.XXXX -->
<input type="text" id="dateTextInput" size="40" pattern="^\d{1,2}.\d{1,2}.\d{4,4}$" placeholder="Please Enter A Date">
<input type="submit" id="addButton" value="Enter a Date">
</form>
<script>
// onsubmit ist just called when dateTextInput is empty or has got valid date
document.getElementById('dateForm').onsubmit = function(e){
e.preventDefault(); // avoid to reload page
var date = document.getElementById('dateTextInput').value;
if(date === ''){ // always use === because == is sometimes buggy
alert('Please enter a date');
}
else{
var convertedDate = date.split('.'); // -> ['03','06','1985']
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
console.log(convertedDate.getTime()); // I think you wanted to get Milliseconds, but this works just as well
}
return false;
};
</script>
When the order of the day, month and year is not right, then just edit the pattern of the input-field and this codeline:
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way?
No array. You should just accept what Date.parse does accept:
whether the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and NaN otherwise.
"recognizable" does refer to Date.parse capatibilites I'd say. It's trivial to implement then:
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
// grab the paragraph
if (valid)
// set the paragraph text accordingly
else
// output something different

Regular expression on textarea

I'm having a bit of trouble validating a form I have, I can check for only letters, numbers and a full stop ("period") in a single text input, but I can't for the life of me get it to work at all on a textarea field.
in my validation I have this:
var usernamecheck = /^[A-Za-z0-9.]{5,1000}$/;
the validation I've tried that doesn't work on the textarea ($ITSWUsers) is:
if(!document.all.ITSWUsers.value.match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
however, the following on a 'input type="text"' works just fine on the same form
if(!document.all.SFUsersName1.value.match(usernamecheck))
{
alert("Usernames can only contain letters, numbers and full stops (no spaces).");
return false;
}
I need it to validate usernames, 1 name per line
e.g.
John.smith
Peter.jones1
these are both OK but the following wouldn't be:
John Smith
David.O'Leary
3rd.username
any help/pointers with this would be greatly appreciated
(I only know basic html/php/javascript)
To validate line by line, I'd use the split function to turn each line into an array. Then, loop through the array and run your RegEx on each line. That way, you can report exactly what line is invalid. Something like this:
<textarea id="ITSWUsers"></textarea>
<button onclick="Validate()">Validate</button>
<script>
var usernamecheck = /^[A-Za-z0-9]{5,1000}\.[A-Za-z0-9]{5,1000}$/;
function Validate()
{
var val = document.getElementById('ITSWUsers').value;
var lines = val.split('\n');
for(var i = 0; i < lines.length; i++)
{
if(!lines[i].match(usernamecheck))
{
alert ('Invalid input: ' + lines[i] + '. Please write the usernames in the correct format (with a full stop between first and last name).');
return false;
}
}
window.alert('Everything looks good!');
}
</script>
I'd trim the input from the textarea using JQuery (or a JS function), and then use this regex:
/^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/
Like so:
function testFunc()
{
var usernamecheck = /^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/;
if(!$.trim(document.all.ITSWUsers.value).match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
}
<textarea id="ITSWUsers" cols="50" rows="10">
John.smith
Peter.jones1
</textarea>
<button onclick="testFunc()">Click Me</button>
See it working here:
http://jsfiddle.net/DkLPB/

Categories