how to show different message on required and invalid? - javascript

can you please tell me how to show different message on required and invalid ?In other word .make a form from json using plugin .In that there are some required parameter .and some I need to validate example "Email".When user press "submit" button if user did not fill the field it show "this field is required" .and if user fill the value but not same patten than it say "invalid value".can we show different message as different situation .
i used this plugin
https://github.com/Textalk/angular-schema-form/blob/master/docs/index.md#validation-messages
and I make this plunker
http://plnkr.co/edit/ZNJO3x3IqajjdMNStJMF?p=preview
angular.module('test',['schemaForm']).controller('FormController', function($scope,$http){
$scope.schema = {
type: "object",
properties: {
name: { type: "string", minLength: 2, title: "Name", description: "Name or alias" ,required:true,"default": "dddd"},
"student": { type: "string", title: "studentname", description: "Name or student" ,required:false},
"email": {
"title": "Email",
"type": "string",
"pattern":"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*",
"description": "Email will be used for evil.",
required:true
},
title: {
type: "string",
required:true,
enum: ['dr','jr','sir','mrs','mr','NaN','dj'],
}
}
};
$scope.form = [
"*",
{
type: "submit",
title: "Save"
}
];

As you may read from the official angular-schema-form documentation
Per default all error messages comes from the schema validator tv4, this might or might not work for you. If you supply a validationMessage property in the form definition, and if its value is a string that will be used instead on any validation error.
If you need more fine grained control you can supply an object instead with keys matching the error codes of tv4. See tv4.errorCodes
Ex.
{
key: "address.street",
validationMessage: {
tv4.errorCodes.STRING_LENGTH_SHORT: "Address is too short, man.",
"default": "Just write a proper address, will you?" //Special catch all error message
}
}
You can also set a global validationMessage in formDefaults see Global Options.
So for more error messages, visit this link

Here is a great blog article that should answer your question: http://www.thebhwgroup.com/blog/2014/08/designing-html-forms-angularjs-part-1/
In particular, check out part 3 "Validation Messages and Styling".
From the article,
<span class="validation-message" ng-show="contactForm.firstName.$error.maxlength">Max length 20</span>
Where the ng-form is named contactForm and the element in question is named firstName. This puts the form on the scope and you can then traverse that to get the errors, and show an error message specifically for each error.

Related

How To Retrieve More Than One "GetValue" From JSON/AJAX search

Ok, I'm struggeling with JSON, AJAX, Javascript and PHP.
Well, actually its only Javascript.
I want to have a input field which operates as a AutoSearch field.
I am using currently EasyAutoComplete.
But that doesnt really matter. What does matter is, that I have to choose one type from the JSON array to be searched. But I want to search both.
Just to make things clear:
- the user should be able to type in "abc" and "123" and find either the number "123456" or "School abc".
- When the user clicks on the result, in both cases the field value should be the number.
Javascript:
$(document).ready(function(){
var options = {
url: function(phrase){
console.log("autocomplete/autocomplete.php?term="+phrase);
return "autocomplete/autocomplete.php?term="+phrase;
},
highlightPhrase: false,
getValue: "instanz_id",
template: {
type: "description",
fields: {
description: "schulname"
}
},
list: {
hideAnimation: {
type: "slide",
time: 400,
callback: function(){}
},
match:{
enabled: true
}
}
};
$("#autocomplete").easyAutocomplete(options);
});
My database structure looks like:
"instanz_id", "schulname"
"123456", "DemoSchule"
Right now, if I type in "123" my JSON return string looks like this:
[{"instanz_id":"123456","schulname":"DemoSchule"}]
And my searchlist: "123456 - DemoSchule". When I click on it, 123456 is the new value of the input field.
How can I get the same item in the searchlist when typing e.g. "Dem" ?
I can change the getValue to "schulname" but then I cannot search using the number...
Can please someone send me in the right direction?

How can I make a field in a meteor Simple Schema equal to a js variable and still let the user fill out the rest of the simple schema?

I am making a meteor web app where the user will click on a html button. Once this button is clicked, the user needs to be directed to another page with some forms generated by a meteor simple schema package. The first field in the simple schema needs to automatically be given a string value of "hello" and then the rest of the fields in the simple schema will be filled out by the user with the input fields on the page. What I am unsure about is how to get the first value automatically set to this string value. Here is some of the code I have:
The simple schema declaration:
LobbySchema = new SimpleSchema({
game: {
type: String,
label: "Game"
},
console: {
type: String,
label: "Console"
},
players: {
type: Number,
label: "Players"
},
mic: {
type: Boolean,
label: "Mic"
},
note: {
type: String,
label: "Note"
},
gamertag: {
type: String,
label: "Gamertag"
},
createdAt: {
type: Date,
label: "Created At",
autoValue: function(){
return new Date()
},
autoform: {
type: "hidden"
}
}
});
The first field there in the schema "game" needs to be given the value "hello" when the html button is clicked. Right now I can assign that value to a javascript variable using the button by having an onclick function:
function getElementText(elementID){
var elementText = "hello";
}
The button would call the getElementText function and have the elementText variable equal "hello". Now I need to assign the the first field in the simple schema to this variable value, "hello", then have it so the user can now fill out the rest of the schema with the input fields, automatically generated into the html with this code:
{{> quickForm collection="Lobby" id="insertLobbyForm" type="insert" class="newLobbyForm"}}
If you do not feel like providing the answer (maybe it happens to be more complicated than I think) then I would be very happy to receive a link to a site that might help me with this. I am also very willing to explain anything about the question if I did not explain the situation well enough above.
You can use the AutoForm hooks like this:
AutoForm.hooks({
app_create: {
before: {
method: function (doc) {
// Do whatever assignment you need to do here,
// like doc['game'] = "hello"; //then
return doc;
}
},
onSuccess: function (formType, result) {
},
onError: function (formType, error) {
}
}
});
Where here app_create is the id of the form you're sending with Autoform.

Meteor js: get full validation message with validatedmethod simpleschema

I am new to Meteor js and I am trying to create a form following the official guide http://guide.meteor.com/methods.html#method-form. It suggests to use mdg:validated-method package and aldeed:simple-schema for validation which are based on mdg:validation-error to return validation error messages to the client. The guide suggests this code then to handle validation
Invoices.methods.insert.call(data, (err, res) => {
if (err) {
if (err.error === 'validation-error') {
// Initialize error object
const errors = {
email: [],
description: [],
amount: []
};
// Go through validation errors returned from Method
err.details.forEach((fieldError) => {
// XXX i18n
errors[fieldError.name].push(fieldError.type);
});
// Update ReactiveDict, errors will show up in the UI
instance.errors.set(errors);
}
}
});
but the problem is that only fieldError.type, fieldError.name and first human readable message from simple-schema are available in err.error. I use translated messages and field labels in simple-schema to get nice understandable validation error messages. So getting just object property name with "required" is unacceptable, especially in the case when message includes min/max constraints for example. I could not find any way to get simple-schema's validation context to retrieve the full list of human readable errors.
So my question is can I get full error messages on the client and how?
Or maybe there are better ways to achieve what I am trying to do?
Thanks in advance
Hi! Recently I have encountered with the same problem.
So I just create pull request with some code enhancement to solve this issue. Now when you submit form and call validated-method from client side like following:
yourMethodName.call(data, (err) => {
if (err.error === 'validation-error') {
console.dir(err, 'error ')
}
});
You will see error object in the console:
{
"errorType": "ClientError",
"name": "ClientError",
"details": [
{
"name": "firstName",
"type": "required",
"message": "First name is required"
},
{
"name": "lastName",
"type": "required",
"message": "Last name is required"
},
{
"name": "phone",
"type": "required",
"message": "Phone is required"
},
{
"name": "email",
"type": "required",
"message": "Email is required"
}
],
"error": "validation-error"
}
So I just copy that from my console output.
In my case, the method is as follows:
export const yourMethodName = new ValidatedMethod({
name: 'my.awesome.method',
validate: new SimpleSchema({
firstName: { type: String },
lastName: { type: String },
phone: { type: Number },
email: { type: String, regEx: SimpleSchema.RegEx.Email }
}).validator({ clean: true }),
run(doc) {
YourCollection.insert(doc);
}
});
If my pull request will be accepted, you can easy use node-simple-schema (it is the next version of meteor-simple-schema).
If it won't you can use my fork.
Hope this helps!
EDIT: Now this feature available in official node-simple-schema package.

how to make view (form)from json using angular?

I am trying to make view from json .When I have array of objects .I am able to make view and validate that view .
If I have this array of object ,in that case I make able to view ,
check plunker
http://plnkr.co/edit/eD4OZ8nqETBACpSMQ7Tm?p=preview
[{
type: "email",
name: "email",
required:true
}, {
type: "text",
name: "name",
required:true
}, {
type: "number",
name: "phonenumber",
required:true
}, {
type: "checkbox",
name: "whant to check"
},
{
type: "url",
name: "server Url"
}];
Now the problem occurred when i have json object .I need to show view from json object .I don't know from where I will start work
I have this json
"displayName": display the name of label which is from of input text
field.
inputValues :represent the type of tmput filled .if it is number then
user fill only number , text then user only fill number ,email then
user fill email , if it switch then it is drop down with given
option.
"required" give if field is required or not ?
Assuming your JSON is coming from a configuration file or a service, you can start by obtaining the JSON as a JSON object:
angular.module('myapp', [])
.controller('MyController', ['$scope', function($scope) {
$scope.outputs = {};
$scope.rawInput = JSON.parse( '{"studentName": "abc", \
"input": {\
"loginUser": {\
"displayDetail": "UserId for login.",\
"displayName": "Login User Id*",\
"inputType": "TEXT",\
(I had to escape returns to allow the pretty printed JSON string to be parsed)
Once you have that, you are nearly there. Now you can just go the level of JSON that you require and construct your inputs array:
$scope.formInputs = $scope.rawInput['input'];
$scope.inputs = [];
angular.forEach($scope.formInputs, function(value, key) {
/* do something for all key: value pairs */
$scope.inputs.push({"type":value.inputType.toLowerCase(),"name":value.name,"required": value.required})
});
Note you should probably do some error checking here - for the purposes of this example, I don't use any. Here is a working plnkr that demonstrates this code.
I haven't got it all to work - you'll have to construct your select or radio button inputs, but I think you should be able to take it from here.
EDIT I have undated the plnkr to make it public

Select method is not validated dynamically

I am using a select method in form and when I click on submit method without filing the form, various errors are shown which I have included in validate methods, like first name required, email required, etc.
So the problem is when I start entering the first name, the error disappears. But the same is not happening in case of select method. When I select certain options there, the error still remains saying, select at least one option. This error goes away when I click submit button. But I want this error to go away when I select at least one option, like in the case of first name when I start typing, the error goes away.
I have included my validation methods in $(document).ready(function()
Any help will be appreciated.
The following is the code snippet:
var newusercontainer = $('#newUsererrorcontainer');
var newuservalidator = $("#newUserForm").validate({
submitHandler: function(form) {
registerUser();
},
errorContainer: newusercontainer,
errorLabelContainer: $("ul", newusercontainer),
wrapper: 'li',
meta: "validate",
rules: {
newUserFirstName: {
required:true,
maxlength:50,
},
sector: {
required: true,
},
},
messages: {
newUserFirstName: {
required: "The First name field is required.",
maxlength: "Please enter with in 60 characters"
},
sector: {
required: "The Sector field is required.",
},
}
});

Categories

Resources