It works, I've tested it. What I want to know is - is this good practice. Obviously I could have just used an associative array and called it. But I wanted to encapuslate it into an object with state.
var View_message = function(div)
{ this.messages =
{
empty: 'Please complete all fields',
empty_bm: 'Please enter both a title and url',
name: 'Only letters or dashes for the name field',
email: 'Please enter a valid email',
same: 'Please make emails equal',
taken: 'Sorry that email is taken',
pass: 'Please enter a valid password, 6-40 characters',
validate: 'Please contact <a class="d" href="mailto:support#archemarks.com">support</a> to reset your password',
url: 'Pleae enter a valid url'
};
this.div = div;
};
View_message.prototype.display = function(type)
{
document.getElementById(this.div).innerHTML=this.messages[type];
};
obj_view = new View_message('test_id')
obj_view.display('empty');
You will be creating a copy of this.messages for each instance of View_message. To prevent that, you could store the messages in the prototype.
Also, you are doing a lookup of the div every time you display a message. I'd store a reference to the div in the constructor instead.
function View_message (div)
{
this.div = document.getElementsById(div);
}
View_message.prototype.messages = {
empty: 'Please complete all fields',
empty_bm: 'Please enter both a title and url',
name: 'Only letters or dashes for the name field',
email: 'Please enter a valid email',
same: 'Please make emails equal',
taken: 'Sorry that email is taken',
pass: 'Please enter a valid password, 6-40 characters',
validate: 'Please contact <a class="d" href="mailto:support#archemarks.com">support</a> to reset your password',
url: 'Pleae enter a valid url'
};
View_message.prototype.display = function(type)
{
this.div.innerHTML = this.messages[type];
};
There's nothing wrong with the way you're doing it, but unless you have a lot more functions associated with those error messages, it seems a little overboard to create a prototype for it and instantiate a new object for it. You could implement the display method in one function that takes the type and the id as arguments.
function displayMessage(type, div) {
var msgs = {
empty: 'Please complete all fields',
empty_bm: 'Please enter both a title and url',
name: 'Only letters or dashes for the name field',
email: 'Please enter a valid email',
same: 'Please make emails equal',
taken: 'Sorry that email is taken',
pass: 'Please enter a valid password, 6-40 characters',
validate: 'Please contact <a class="d" href="mailto:support#archemarks.com">support</a> to reset your password',
url: 'Pleae enter a valid url'
};
document.getElementById(div).innerHTML = msgs[type];
}
If you call it a lot, you could even put the msgs structure into a closure so it doesn't have to be evaluated each time you call it.
Related
I am new to ReactJs, I am Using Ant-design For Registration Form and applied some validation Rules. I want to validate User when user enter something in fields, message ( Username must be Unique ) is shown to the user for guidance . But when I enter something Error is occur Unknown rule type username.
Code of Form
<FormItem>
{getFieldDecorator('username', {
rules: [
{
type: 'username',
message: 'Username Must be Unique!',
},
{
required: true,
message: 'Please Enter Your Username',
},
],
})(<Input placeholder="Username" />)}
</FormItem>
You must be confusing type with something else.
According to this page: https://ant.design/components/form/ , type will rather be referenced to something like string or boolean.
EDIT:
...
{
type: string,
message: 'Username Must be a string',
},
...
I'm using jquery validation plugin and need to use localization for different language.
The original code would be like this
$('#form').validate({
rules: {
'checkbox1[]': { required: true },
'email': { required: true,
email: true
},
},
messages: {
'checkbox1[]': "Please choose at least 3",
email: {
required:'Please input email',
email: 'Please input valid email'
}
}
});
If I use localization, my message_en.js would be:
$.extend($.validator.messages, {
required: "Please choose your answer.",
email: "Please input valid email.",
});
However, I shared the "required" message in email field. It means that if I didnt input email, the error message would become "Please choose your answer.". Obviously, it is not appropriate.
So, how can I separate the error message?
I have used the code below to validate an email field.
Email: ko.observable('').extend({
required: {
message: 'Email address is required.'
},
pattern: {
params: "^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
message: "Please enter a valid email address"
}
}),
Required validation is working when pattern is not there. However, I want email to be required as well as to follow a specific pattern as mentioned in a regular expression.
It is not working at the moment.
It works, but your pattern seems wrong, I took one of the internet and it works
http://jsfiddle.net/oefst8fa/
var vm = {
email: ko.observable('').extend({
required: true,
pattern: {
params: /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
message: "Please enter a valid email address"
}
})
};
I Use jquery.validate.js for field validation.
Its display error messages as per declare in .js file for appropriate field.
I use this code for custom validation for email field.
<script type="text/javascript">
$().ready(function() {
$("#formcustomplan").validate({
email: {
required: true,
email: true
},
messages: {
email: "Email is required in valid format"
}
});
});
</script>
Its display message like that "Email is required in valid format"
But I want that error message fetch email id and display it in error message.
(Ex. if I enter test.com in email box. it should display "test.com is not valid email" in error message)
Here is Fiddle
JQuery Validate actually supports functions as messages directly, so you don't have to do anything super hacky to make this work. It is not well documented but you can do this:
messages: {
email: {
email: function (params, element) {
return '"'+$(element).val()+'" is not a valid value';
}
}
}
Quote from the docs:
Each message can be a String or a Callback. The callback is called in
the scope of the validator, with the rule’s parameters as the first
argument and the element as the second, and must return a String to
display as the message.
Working example: http://jsfiddle.net/ryleyb/XUM8k/11/
You can reset the default email validation message by using:
$.validator.messages.email = "Your custom message for email field"
In your case, you can prepend the new value from user's input to the custom message. Here is the trick using keyup:
$('.email').keyup(function () {
$.validator.messages.email = $('.email').val() + ' is not valid email';
});
$("#formcustomplan").validate({
email: {
required: true,
email: true
}
});
Updated Fiddle
I have a form that collects some personal information from the end user and triggers some JS validation functions. For simplistic examples lets just say the form has first name, last name, and email address.
Now once the form is filled out and submitted, if I go back to it my browser pre-populates the form like you would expect. The problem is when I go to submit (without changing any fields or tabbing through them) the plugin does not go back and validate those fields (if they have been pre-populated.
I am not sure WHY it is not validating the pre-populated fields. And I am not sure how to get it to. Does anyone have any ideas? I am running the latest version of jQuery and the validate plugin (http://jqueryvalidation.org/).
Sample code:
$(document).ready(function() {
var rules = {
FirstName: 'required',
LastName: 'required',
EmailAddress: {
required: true,
customEmail: true,
checkAccountExists: true
}
};
//And field specific (and even validation type specific) error messages
var messages = {
FirstName: 'Your first name is required.',
LastName: 'Your last name is required.',
EmailAddress: {
required: 'Your email address is required.',
customEmail: 'You must enter a valid email address.',
checkAccountExists: 'We already have an account with that email address. Please login.'
}
};
$('#applicationForm').validate({
//debug: true,
rules: rules,
messages: messages,
errorElement: 'span'
});
});
jQuery.validator.addMethod('customEmail', function(value, element) {
return this.optional(element) || /[A-z0-9._%-+]{1,}#[A-z0-9._%-]{1,}\.[A-z0-9._%-]{1,}/.test(value);
}, 'Invalid email address entered.');
jQuery.validator.addMethod('checkAccountExists', function(value, element) {
if (this.optional(element)) {
return true;
}
var url = $(element).attr('checkEmailUrl');
$.ajax({
type: 'GET',
data: {EmailAddress: value, check: true},
dataType: 'json',
url: url,
success: function(response) {
var dataArray = jQuery.parseJSON(response);
//If it exists then trigger the popup
if (dataArray.result == 'EXISTS') {
kclHelpers.showEmailExistsModal(value);
}
}
});
return true; //If it exists the popup will handle it. We are just using this to trigger it
}, 'An account under the specified email address already exists. Please sign in.');
A simple solution that I employ is just to trigger the blur event already bound to elements you want to validate. You can check the value of each element to determine if they should be validated which prevents this operation from triggering them before the user has interacted.
$(window).load(function() {
//pre-highlight fields with values
$('input[type=text], input[type=email], input[type=url], input[type=password], select').filter(function() {
return $.trim($(this).val()) != '';
}).blur();
});