0

I have the following json

success{ "fname": [ "The fname field is required." ], "lname": [ "The lname field is required." ], "email": [ "The email field is required." ], "password": [ "The password field is required." ], "password_confirmation": [ "The password confirmation field is required." ] }

what i do is this,if the value contains field is required then console.log it. i saved the json in var data

 angular.forEach(data, function(value, key)
                {
                    if( value ==("field is required")){
                        console.log (key)
                    }
               })

I tried .contains, .match, nothing is working

noor
  • 651
  • 1
  • 8
  • 19

4 Answers4

1

Try:

                if( value.indexOf("field is required") > -1){
                    console.log (key)
                }

This will check if the string has "field is required".

Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
  • i get this error : ionic.bundle.js:25642 TypeError: Cannot read property 'indexOf' of null – noor Jul 25 '16 at 04:51
1

You also got the includes method.

Here the doc for includes : http://www.w3schools.com/jsref/jsref_includes.asp

And the doc for IndexOf : http://www.w3schools.com/jsref/jsref_indexof.asp

I personally find the IndexOf solution a little dirty as it is not made for this, but it seems to be the most common solution.

You could also research in StackOverflow before asking, here is the answer of your question :

How to check whether a string contains a substring in JavaScript?

Community
  • 1
  • 1
Alburkerk
  • 1,564
  • 13
  • 19
0

If your JSON vales are ["The --- field is required"] and you are testing string equality with "field is required", then your if condition will never evaluate to true.

You need to get the substring portion of your value if that is what you want to evaluate the condition on. You can use string split, search, substr, or another string method to get that portion of the value: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

You need to use a regex with .match() or .search(). You could also use

 var idx = value.indexOf('field');
 var str = value.slice(idx);
 if( str == "field is required" )...
developer033
  • 24,267
  • 8
  • 82
  • 108
Jinw
  • 428
  • 5
  • 10
0
angular.forEach(data, function(value, key){
  if(value.indexOf("field is required") > -1){
     console.log(key);
    }
 });
amit
  • 406
  • 4
  • 6
  • i get this error : ionic.bundle.js:25642 TypeError: Cannot read property 'indexOf' of null – noor Jul 25 '16 at 04:51