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
Related
I'm beginner at using JavaScript, and I have read documentation of RegExp and went trough couple of examples but I can't to figure it out how to use it properly.
I have a form which contains 5 input fields. I need to use RegExp to validate user input into form. The forbidden values are
( ) { } ' ! # “ \ /
Other characters are allowed but before submitting a form all input field must be entered (no blank/empty fields are allowed).
Input field id="unos_naziv_proizvoda" must contain at least 5 characters and start with capital letter.
Input field id="unos_opis_proizvoda" must contain at least 3 sentences. Sentence starts with a capital letter and end with a dot.
Input field id="unos_datum_proizvodnje" which is date of manufacturing must be in form of dd.mm.yyyy, can't be in the future (must be lower or same as today) and must be type text
Here is HTML code:
<form id="forma_prijava" class="forma_novi_proizvod" action="http://barka.foi.hr/WebDiP/2016/materijali/zadace/ispis_forme.php" method="POST">
<label for="unos_naziv_proizvoda">Naziv proizvoda</label>
<input type="text" name="naziv_proizvoda[15]" id="unos_naziv_proizvoda" placeholder="Unesite naziv proizvoda" maxlength="15">
<label for="unos_opis_proizvoda">Opis proizvoda</label>
<textarea name="opis_proizvoda" id="unos_opis_proizvoda" placeholder="Ovdje unesite opis proizvoda" rows="50" cols="100"></textarea>
<label for="unos_datum_proizvodnje">Datum proizvodnje</label>
<input type="date" name="datum_proizvodnje" id="unos_datum_proizvodnje">
<label for="unos_vrijeme_proizvodnje">Vrijeme proizvodnje</label>
<input type="time" name="vrijeme_proizvodnje" id="unos_vrijeme_proizvodnje">
<label for="unos_kolicina_proizvodnje">Količina proizvodnje</label>
<input type="number" name="kolicina_proizvodnje" id="unos_kolicina_proizvodnje" placeholder="Unesite količinu proizvodnje" min="1">
<button type="Submit" value="Submit">Dodaj proizvod</button>
<button type="Reset" value="Reset">Poništi unos</button>
</form>
Here is js code:
window.onload = function(){
var provjeri = function(){
var re = new RegExp(/[^(){}'!#"\/]/, g);
var uzorak = document.getElementById("forma_prijava"); //id of a form //
var ok = re.test(uzorak.value);
if(!ok){
alert("Niste unijeli valjani tekst"); //alert message if it's not valid input //
return false;
}
else{
alert("OK"); // message if it's valid input //
return true;
}
};
document.getElementById("forma_prijava").addEventListener("oninput", provjeri);
};
I don't know should I use it on a whole form as one unit or on each input field separately because I have different types of input fields (two are text and others are date, time and number). If someone could provide more understandable explanation when providing an example I would appreciate that. :)
Just to point it out once again, I strictly must use RegExp (pure JavaScript), no other libraries or frameworks do not come in mind!
Thank you in advance!
You can use property pattern of the input Tag
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.
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 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